0%

leetcode 1 Solution

代码解析

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
package com.demo.s1;

import java.util.HashMap;
import java.util.Map;

/**
* 给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
*/
public class Solution {

public int[] twoSum(int[] nums, int target) {
//定义返回结果
int[] ret = new int[2];
//缓存出现过的数<数字和下标>
Map<Integer, Integer> cache = new HashMap<Integer, Integer>();
for(int i =0; i< nums.length; i++) {
//另一个数字之前出现过
if(cache.containsKey(target -nums[i] )) {
ret[0] = cache.get(target -nums[i]);
ret[1] = i;
break;
} else {
//没出现过则缓存下来
cache.put(nums[i], i);
}
}
return ret;
}
public static void main(String[] args) {
int[] nums = new int[]{1,2,3,4,5};
int target = 5;
new Solution().twoSum(nums, target);
}
}