一、C语言暴力解决
int* twoSum(int* nums, int numsSize, int target, int* returnSize){
int *a = (int *)malloc(sizeof(int) * 2);
int i, j;
for (i = 0; i < numsSize - 1; i++) {
for (j = i + 1; j < numsSize; j++) {
if (nums[i] + nums[j] == target) {
a[0] = i;
a[1] = j;
*returnSize = 2;
return a;
}
}
}
*returnSize = 0;
return a;
}
二、C++使用map实现
class Solution {
public:
vector<int> twoSum(vector<int>& nums, int target) {
vector<int> arr;
map<int, int> m; //map不会插入重复数据
for (int i = 0; i < nums.size(); i++)
{
m.insert(make_pair(nums[i], i));
}
//按数组顺序遍历
for (int i = 0; i < nums.size(); i++)
{
if (m.count(target - nums[i]) > 0 && m[target - nums[i]] != i) {
arr.push_back(i);
arr.push_back(m[target - nums[i]]);
break;
}
}
return arr;
}
};