您的位置:首页 > 其它

[leetcode 1] Two Sum

2016-03-15 22:25 357 查看
Question:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

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

Example:

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

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


分析:

暴力法很简单,二重循环,但是超时了;

可以声明一个辅助数组,是对原数组的拷贝,这样,可以将辅助数组进行排序,排序后通过左右两个索引指针就可以判断是哪两个值相加为target;

然后在原数组中找到这两个值所对应的下标。

代码如下:

<span style="background-color: rgb(255, 255, 255);"><span style="font-size:14px;">class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> res(2);
vector<int> cp(nums);

sort(nums.begin(),nums.end());
int left = 0;
int right = nums.size()-1;
while(left < right){
int sum = nums[left] + nums[right];
if(sum < target)
++left;
else if(sum > target)
--right;
else{
break;
}
}
for(int i = 0; i < nums.size(); ++i){
if(cp[i] == nums[left]){
left = i;
break;
}
}
for(int i = 0; i < nums.size(); ++i){
if(cp[i] == nums[right] && i != left){
right = i;
break;
}
}
res[0] = min(left,right);
res[1] = max(left,right);
return res;

//暴力法
/* for(int i = 0; i < nums.size()-1; ++i){
for(int j = i+1; j < nums.size(); ++j){
if(nums[i] + nums[j] == target){
res.push_back(i);
res.push_back(j);
break;
}
}
}
return res;*/
}
};</span></span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: