【LeetCode】167. Two Sum II - Input array is sorted


Two Sum II - Input array is sorted

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

 

典型的雙指針問題。

初始化左指針left指向數組起始,初始化右指針right指向數組結尾。

根據已排序這個特性,

(1)如果numbers[left]與numbers[right]的和tmp小於target,說明應該增加tmp,因此left右移指向一個較大的值。

(2)如果tmp大於target,說明應該減小tmp,因此right左移指向一個較小的值。

(3)tmp等於target,則找到,返回left+1和right+1。(注意以1為起始下標)

時間復雜度O(n): 掃一遍

空間復雜度O(1)

ps: 嚴格來說,兩個int的加和可能溢出int,因此將tmp和target提升為long long int再進行比較更魯棒。

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<int> ret(2,-1);
        int left = 0;
        int right = numbers.size()-1;
        while(left < right)
        {
            int tmp = numbers[left]+numbers[right];
            if(tmp == target)
            {
                ret[0] = left+1;
                ret[1] = right+1;
                return ret;
            }
            else if(tmp < target)
            //make tmp larger
                left ++;
            else
            //make tmp smaller
                right --;
        }
    }
};

 

以下是我的測試用例,全部測試通過:

int main()
{
    Solution s;
    int A[4] = {2, 7, 11, 15};
    vector<int> numbers1(A, A+4);
    vector<int> ret = s.twoSum(numbers1, 9);
    cout << ret[0] << ", " << ret[1] << endl;

    int B[2] = {1, 1};
    vector<int> numbers2(B, B+2);
    ret = s.twoSum(numbers2, 2);
    cout << ret[0] << ", " << ret[1] << endl;

    int C[3] = {1,2,3};
    vector<int> numbers3(C, C+3);
    ret = s.twoSum(numbers3, 5);
    cout << ret[0] << ", " << ret[1] << endl;

    return 0;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM