問題內容是:給定一個數組,給定一個數字。返回數組中可以相加得到指定數字的兩個索引。
比如:給定nums = [2, 7, 11, 15], target = 9
那么要返回?[0, 1]
,因為2 + 7 = 9
?
這道題的優解是,一次遍歷+HashMap:
先去Map中找需要的數字,沒有就將當前的數字保存在Map中,如果找到需要的數字,則一起返回
代碼:
public int[] testTwoSum(int[] nums, int target) {Map<Integer, Integer> map = new HashMap<>();for (int i = 0; i < nums.length; i++) {int complement = target - nums[i];if (map.containsKey(complement)) {return new int[] { map.get(complement), i };}map.put(nums[i], i);}throw new IllegalArgumentException("No two sum solution");}@Testpublic void test4(){int[] nums = {2, 7, 11, 15};int target = 9;int[] j = testTwoSum(nums, target);System.out.println(Arrays.toString(j));}
?