給定一個數組,和一個目標值,返回數組中兩個和為目標值的下標,假設結果只有一個
使用hashMap存儲數組元素值和下標,當map中含有target-num[i]的鍵時,說明已查找到。
public int[] twoSum(int[] nums, int target) { int[] re=new int[2]; HashMap<Integer, Integer> map = new HashMap<>(); for(int i=0;i<nums.length;i++){ if(map.containsKey(target-nums[i])){ re[0]=map.get(target-nums[i]); re[1]=i; return re; }else{ map.put(nums[i], i); } } return re; }新聞熱點
疑難解答