这是leetcode第一题,通过较为简单。
第一题用来测试的,用的c,直接暴力法过,
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* twoSum(int* nums, int numsSize, int target) {
static int a[]={};
for(int i=;i<numsSize-;i++)
for(int j=i+;j<numsSize;j++)
if(nums[i]+nums[j]==target){
a[]=i;
a[]=j;
return a;
};
return ;
}
官方还提供了hash表法,用的java
public int[] twoSum(int[] nums, int target) {
Map<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
map.put(nums[i], i);
}
for (int i = 0; i < nums.length; i++) {
int complement = target - nums[i];
if (map.containsKey(complement) && map.get(complement) != i) {
return new int[] { i, map.get(complement) };
}
}
throw new IllegalArgumentException("No two sum solution");
}