LeetCode刷题之TWO_SUM_0001

java版本:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 public static void main(String[] args) {
int[] nums = {-1,-2,-3,-4,-5};
int[] sum = twoSum(nums, -8);
System.out.println(Arrays.toString(sum));
}

//方法一,暴力破解 试图用过滤条件减少循环次数 为什么不换一种方式?
public static int[] twoSum(int[] nums, int target) {

int[] reNums = new int[2];
for (int i = 0; i < nums.length;i++) {
//if(target - nums[i] >= 0){
for (int j = i + 1; j < nums.length; j++) {
//if(target -nums[i] - nums[j] < 0) continue;
if((nums[i] + nums[j]) == target){
reNums[0] = i;
reNums[1] = j;
break;
}
}
//}
}
return reNums;
}
//第二种方式:哈希表 HashMap
public static int[] twoSum_hash(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
int tempR = target - nums[i];
if(map.containsKey(tempR)){
return new int[]{map.get(tempR),i};
}
map.put(nums[i],i);
}
return null;
}
苏小南 wechat
扫一扫,点个关注哦!
生活不易,记得打个赏