HashMap
class Solution {public int[] twoSum(int[] nums, int target) {int a = 0, b = 0; // 返回两个索引HashMap<Integer, Integer> hm = new HashMap<>(); // key是值,value是索引for (int i = 0; i < nums.length; i++) {if (!hm.containsKey(nums[i])) {hm.put(nums[i], i);} else { // 重复元素先判断是不是组成targetif (nums[i] * 2 == target) {a = hm.get(nums[i]);b = i;return new int[]{a, b};}}}for (int i = 0; i < nums.length; i++) {int div = target - nums[i];hm.remove(nums[i]);if (hm.containsKey(div)) {a = i;b = hm.get(div);break;}}return new int[]{a, b};}
}