雙指針?biāo)惴ń忸}-leetcode167 兩數(shù)之和 II - 輸入有序數(shù)組

[167] 兩數(shù)之和 II - 輸入有序數(shù)組
https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted/description/
algorithms
Easy (46.85%)
Total Accepted: 15.9K
Total Submissions: 33.9K
Testcase Example: '[2,7,11,15]\n 9'
給定一個(gè)已按照升序排列 的有序數(shù)組,找到兩個(gè)數(shù)使得它們相加之和等于目標(biāo)數(shù)。
函數(shù)應(yīng)該返回這兩個(gè)下標(biāo)值 index1 和 index2,其中 index1 必須小于 index2。
說明:
返回的下標(biāo)值(index1 和 index2)不是從零開始的。
你可以假設(shè)每個(gè)輸入只對(duì)應(yīng)唯一的答案,而且你不可以重復(fù)使用相同的元素。
示例:
輸入: numbers = [2, 7, 11, 15], target = 9
輸出: [1,2]
解釋: 2 與 7 之和等于目標(biāo)數(shù) 9 。因此 index1 = 1, index2 = 2 。

這是一道典型的雙指針?biāo)惴}, 利用有序數(shù)組的特點(diǎn), 取頭尾兩個(gè)下標(biāo)作為初始值, 兩數(shù)之和大于target則將end左移一位, 兩數(shù)之和小于target則將start右移一位.

class Solution: NSObject {
    
    func twoSum(_ numbers: [Int], _ target: Int) -> [Int] {
        
        if numbers.count > 0 {
            
            var start = 0
            var end = numbers.count - 1
            var account = numbers[start] + numbers[end]
            while (account != target && start < end) {
                
                if account > target {
                    
                    end -= 1
                } else {
                    
                    start += 1
                }
                account = numbers[start] + numbers[end]
            }
            if account == target {
                
                start += 1
                end += 1
                return [start, end]
            } else {
                
                return []
            }
        } else {
         
            return []
        }
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容