// 暴力法 publicstaticint[] twoSum(int[] nums, int target) { int[] a = newint[2]; for (int i = 0; i < nums.length; i++) { for (int j = i + 1; j < nums.length; j++) { if (nums[i] + nums[j] == target) { a[0] = i; a[1] = j; break; } } }
return a; }
// 哈希 publicstaticint[] twoSum1(int[] nums, int target) { HashMap<Integer, Integer> mymap = new HashMap<>(); for(int i = 0; i < nums.length; i++){ mymap.put(nums[i], i); }
for(int i = 0; i < nums.length; i++){ int t = target - nums[i]; if(mymap.containsKey(t) && mymap.get(t) != i ){// 注意后面这个条件,题目要求 returnnewint[] {i,mymap.get(t)}; } }
returnnull;
}
publicstaticvoidmain(String[] args){ int[] nums = { 2,11,15, 7}; int target = 9; int []result = twoSum1(nums, target);
for (int i = 0; i < result.length; i++) { System.out.println(result[i]); }