题目:
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].
解法一:
这道题就是找到数组中两个数字相加和为定值,输出该元素下标,小的在前面。最容易想到的方法就是双重循环,把整个数组遍历一遍之后输出下标。
int* twoSum(int* nums, int numsSize, int target) {
int (*res)[2];
res = (int*)malloc(10*sizeof(int));
for(int i = 0; i < numsSize; i++){
for(int j = i+1; j < numsSize; j++){
if(nums[i] + nums[j] == target){
(*res)[0] = i;
(*res)[1] = j;
return res;
}
}
}
return res;
}
但是这个算法的时间复杂度为O(n^2) ,还可以找到更好的解法。
解法二
参考网上的解法,使用两个指针的方法。主要思想是:
定义一个新的数组cdata,将原数组中的值复制进此数组,并进行从小到大的排序。
定义两个变量 i 和 j ,使 i 指向cdata的第一个元素,j 指向cdata的最后一个元素,计算cdata[i]+cdata[j]的值sum并和target进行比较。
如果sum
解法三
将数组中的元素存入map中,然后进行查找。
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> index;
map<int,int> m;
int t;
for(int i = 0; i < nums.size(); i++){
m[nums[i]] = i;
}
for(int i = 0; i < nums.size(); i++){
t = target - nums[i];
if(m.count(t) && m[t]!=i){
index.push_back(i);
index.push_back(m[t]);
return index;
}
}
return index;
}
};