Two Sum - Input array is sorted解题报告

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 twoSum(vector &nums, int target) { vector 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解题报告)