LeetCode #151 Two Sum
LeetCode #151 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
代码:
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> temp = numbers;
sort(temp.begin(), temp.end());
//cout<<*numbers.begin()<<numbers.at(3)<<endl;
int index1,index2;
int i = 0,j = temp.size()-1;
while(i < j){
//cout<<i<<j<<endl;
int sum = temp[i] + temp[j];
if(sum == target){
break;
}else if(sum > target){
j--;
}else{
i++;
}
for(int k = 0; k < temp.size(); k++){
if(numbers[k] == temp[i])
{index1 = k+1;break;}
}
for(int k = temp.size()-1; k >= 0; k--){
//cout<<k<<endl;
if(numbers[k] == temp[j])
{index2 = k+1;break;}
}
if(index1 > index2){
int temp = index1;
index1 = index2;
index2 = temp;
}
vector<int> result;
result.push_back(index1);
result.push_back(index2);
return result;
}
};
int main()
{
//cout << "Hello world!" << endl;
int nums[4] = {4,3,2,1};
vector<int> numbers(&nums[0], &nums[4]);
Solution solution;
vector<int> re = solution.twoSum(numbers, 5);
cout<<re.at(0)<<" "<<re.at(1);
return 0;
}
总结:
- 一开始什么也没考虑写了个二重循环,结果时间超限
- 看了解析之后重写,结果忘记考虑
index1 < index2
WA了 - 之后又加了个判断才AC
- 时间复杂度O(nlogn) 还有个O(n)的解,要用map,以后写