题目来自LeetCode:https://oj.leetcode.com/problems/two-sum/
题目如下:
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
思路:
target指的是数组中某两个数的和,也就是这两个数是小于等于target的数。比较笨的方法是一个一个的遍历。返回所有的结果。
最简单的方法:
这种方法能实现功能,但是绝对不是一个好方法,当数组不断的变大的时候,计算需要的时间也就越来越长,然后就GameOver了。太忧伤了。
1: class Solution {
2: public:
3: vector<int> twoSum(vector<int> &numbers, int target) {
4: int index1 = -1 ;
5: int index2 = -1 ;
6: for(int i = 0 ; i < numbers.size();i++)
7: {
8: if(numbers[i] < target)
9: {
10: for(int j = 0 ; j < numbers.size() ; j++)
11: {
12: if(j == i)
13: continue ;
14:
15: if(numbers[i] + numbers[j] == target)
16: {
17: index1 = i + 1 ;
18: index2 = j + 1 ;
19: if(index1 > index2)
20: {
21: int temp = 0 ;
22: temp = index1 ;
23: index1 = index2 ;
24: index2 = temp ;
25: }
26: }
27: }
28: }
29: }
30:
31: vector<int> ret ;
32: ret.push_back(index1) ;
33: ret.push_back(index2) ;
34: return ret ;
35: }
36: };
下面介绍一种简便的方法,是从LeetCode中找到的,
1: class Solution {
2: public:
3: vector<int> twoSum(vector<int> &num, int tag) {
4: int length = num.size(),left = 0,right = length - 1 ;
5: vector<pair<int ,int>> ans ;
6: for(int i = 0 ; i < length ; i++)
7: {
8: ans.push_back(make_pair(num[i],i+1)) ;
9: }
10: sort(ans.begin(),ans.end()) ;
11:
12: while(left < right){
13: int x = ans[left].first + ans[right].first ;
14: if(x < tag)
15: {
16: left++ ;
17: }
18: else if(x > tag)
19: {
20: right-- ;
21: }
22: else
23: {
24: vector<int> a {ans[left].second,ans[right].second} ;
25: sort(a.begin(),a.end()) ;
26: return a ;
27: }
28: }
29: }
30: };
这个方法遍历的次数要少很多,简单介绍下这个方法:
先是用pair将num和他的index成对儿存储起来,得到ans,然后对ans 进行排序,使其从小到大排列。
取头尾两个值相加,根据相加的和来判断是否是要找的数值。
大的时候动右边的值,小的时候动作边的值。这样就会越来越接近最终结果。
两个值都是往中间走,所以,大的时候要动右边的值,这样才能缩小结果,小的时候要动左边的值这样才能变大。
好了,就这样吧!希望自己天天进步。
浙公网安备 33010602011771号