标签:
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
Array Hash Table
开始想直接按正常的最简单方法两个循环来做,结果发现提交时,超出了内存,显然这道题不能这样做
接下来,又想是不是顺序的,就把后面的数给砍掉,结果发现是无需的数列
在接下来,又想把比目标数字大的全部砍掉,结果发现有负数,这种方法也不行。
lass Solution { public: vector<int> twoSum(vector<int> &numbers, int target) { vector<int> last_result; vector<int> temp; int len=numbers.size(); int realy_size; for(int i=0;i!=len;i++) { if(numbers[i]<target) { realy_size=i; temp.push_back(numbers[i]); } } realy_size=temp.size(); for(int i=0;i!=realy_size-1;++i) { for(int j=i+1;j!=realy_size;++j) { if(numbers[i]+numbers[j]==target) { last_result.push_back(i+1); last_result.push_back(j+1); return last_result; } } } return last_result; } };
看来非得需要用hash表来做
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4434339.html