Two Sum - Input array is sorted解

作者: 黑山老水 | 来源:发表于2017-06-01 11:10 被阅读4次

    Description:

    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.

    Example:

    Given nums = [2, 7, 11, 15], target = 9
    return [1, 2]

    Link:

    http://www.lintcode.com/en/problem/two-sum-input-array-is-sorted/

    解题思路:

    当input array已经被排序的时候,数组中两个数相加最小的情况是头两个数相加,相加最大的情况是最后两个数相加。所以用一头(start)一尾(end)两个指针,当nums[start] + nums[end] > target的时,头指针向后走,当nums[start] + nums[end] < target时,尾指针向前走。当相等时就是本题要找的两个index。否则即无解。

    Time Complexity:

    O(n)

    完整代码:

    vector<int> twoSum(vector<int> &nums, int target) { vector<int> result; if(nums.size() < 2) return result; int start = 0, end = nums.size() - 1; while(start < end) { int temp = nums[start] + nums[end]; if(temp < target) start++; else if(temp >target) end--; else { result.push_back(start + 1); result.push_back(end + 1); return result; } } return result; }

    相关文章

      网友评论

        本文标题:Two Sum - Input array is sorted解

        本文链接:https://www.haomeiwen.com/subject/sywsfxtx.html