# 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 < index2WA了 - 之后又加了个判断才AC
- 时间复杂度O(nlogn) 还有个O(n)的解,要用map,以后写
本文详细解析了LeetCode上的经典题目TwoSum,提供了高效的算法思路和C++代码实现,通过排序和双指针技巧找到数组中两个数相加等于目标值的下标。
2526

被折叠的 条评论
为什么被折叠?



