利用HashMap实现leetcode102题首先添加数组到HashMap中,接着遍历该HashMap即可。 public static void main(String[] args) { int[] a = {2, 7, 11, 14}; int target = 16; for (int i = 0; i < two_Sum(a, target).length; i++) { System.out.println(two_Sum(a, target)[i]); } } public static int[] two_Sum(int[] nums, int target) { int[] result = {-1, -1};//如果没有找到,则返回此值 Map<Integer, Integer> map = new HashMap<>(); //首先将数组元素添加到HashMap中,key为数组值,value为数组下标 for (int i = 0; i < nums.length; i++) { map.put(nums[i], i); } for (int i = 0; i < nums.length; i++) { int temp = target - nums[i]; if (map.containsKey(temp) && i != map.get(temp)) { result[0] = i; result[1] = map.get(temp); return result; } } return result; }