1. Two Sum
题目链接:1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
解法一
暴力法,时间复杂度n2, 空间复杂度1
遍历数组,对于每个数num1, 再遍历一遍去寻找num2 = target - num1存不存在。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> a(0);
int len = nums.size();
int flag = 0;
for(int i = 0; i < len;++i){
int lnum = target - nums[i];
for(int j = 0;j < len;++j){
if(j == i){
continue;
}
if(nums[j]+nums[i] == target){
a.push_back(i);
a.push_back(j);
flag = 1;
break;
}
}
if(flag){
break;
}
}
return a;
}
};
解法二
时间复杂度为nlogn 空间复杂度为nlogn
用set来做,对于每个遍历一遍数组,把每个数num1的解num2 = target - num1存在set里。
再次遍历数组,如果当下的值num1在set里找的到,说明是num1和target-num1存在在数组里,把他们位置找出来就行。
You may assume that each input would have exactly one solution。
题目已经告诉了,可以断定只有一组精确的解,
and you may not use the same element twice.
因为相同的元素不能用两次,所以必须要判重,即是两个数的位置是否相同。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> a(0);
int len = nums.size();
set<int> s;
for(int i = 0;i < len;++i){
s.insert(target - nums[i]);
}
for(int i = 0;i < len;++i){
if(s.find(nums[i])!=s.end()){
int num1 = nums[i];
int num2 = target - nums[i];
int i ;
int pos = 0;
for(i = 0;i<len;++i){
if(num1 == nums[i]){
pos =i;
break;
}
}
a.push_back(pos);
for(i=0;i<len;++i){
if(num2 == nums[i]){
pos = i;
}
}
a.push_back(pos);
if(a[0] == a[1]){
a.clear();
continue;
}
break;
}
}
return a;
}
};