您的位置:首页 > 职场人生

LeetCode:Two Sum II - Input array is sorted

2017-05-03 17:39 393 查看
Problem:

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 and you may not use the same element twice.

For example:

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

问题的意思就是,给我们一个已经排好序的数组,然后再给一个target数,从这个数组中找出两个数字,是他们的和等于target,然后返回他们的位置,但不是下标,这个需要注意下,例子给的很清楚。

首先给一种很简单的思路,但是复杂度为O(n^2),算法复杂度很高;大概是遍历两次数组,找到满足条件的数字,只需要两个for循环,思路简单也很容易理解;第二种时间复杂度为O(N)这也是复杂度最低的算法了,有点类似于二分法的思想;就是先从数组的两端开始比较,如果两个数和的结果大于target那么最后那个数字向前移动,否则前面一个数字向前移动,当某两个数字的和等于target时结束while循环。

vector<int> twoSum(vector<int>& nums, int target) {
vector<int> vec;
int first=0,last=nums.size()-1;
while(nums[first]+nums[last]!=target)
{
if(nums[first]+nums[last]<target)
first++;
else
last--;
}
vec.push_back(first+1);
vec.push_back(last+1);
return vec;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  面试 leetcode 算法