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].
思路:1.枚举判断每个元素与另一个元素之和是否等于目标值
2.哈希查找,将所有元素存入hashmap中,目标值减去每个元素等于某个值。看这个值是否等于剩下某个元素。
1 int* twoSum(int* nums, int numsSize, int target) { 2 int *a = (int *)malloc(2*sizeof(int)); 3 int num = 0; 4 for(int i=0;i<numsSize;i++){ 5 for(int j=i+1;j<numsSize;j++){ 6 if(nums[i]+nums[j]==target){ 7 a[0] = i; 8 a[1] = j; 9 } 10 } 11 } 12 return a; 13 14 }