题目
Given an array of integers, 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
解题思路
给出一个数组合一个数,如果两个数的和等于所给的数,求出该两个数所在数组中的位置。
这个题也挺常见的,就是两个指针,从前后两个方向扫描。但是本题有以下几个需要的点:
1. 所给数组不是有序的;
2. 返回的下标是从1开始的,并且是原来无序数组中的下标;
3. 输入数组中可能含有重复的元素。
好了,把以上三点想到的话,做这个题应该不会有啥问题。
具体方法:把原数组拷贝一份,求出拷贝的数组中符合题意的两个数;再去原数组中找到前面两个数的位置,返回即可。
代码实现
class Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> ret; int n = numbers.size(); if(n<=0) return ret; int i=0, j=n-1; int sum; vector<int> copy(numbers); sort(copy.begin(), copy.end()); while(i<=j){ sum = copy[i]+copy[j]; if(sum>target) --j; else if(sum<target) ++i; else break; } if(i<=j){ for(int k=0; k<n; ++k){ if(numbers[k] == copy[i]){ ret.push_back(k+1); }else if(numbers[k] == copy[j]){ ret.push_back(k+1); } } } return ret; } };
--------------------------------------------------------------------------------------------------------------------------------
如果你觉得本篇对你有收获,请帮顶。
另外,我开通了微信公众号--分享技术之美,我会不定期的分享一些我学习的东西.
你可以搜索公众号:swalge 或者扫描下方二维码关注我
(转载文章请注明出处: http://blog.csdn.net/swagle/article/details/29200949
)
[LeetCode] Two Sum [17]