• 2.5

    • 忘了 map 是 put 了,秒了
  • 1.22

    • 数作 Key,下标作 val
    • 不能是同一个数字哦,所以要再加一个判定条件
    • map 的 api 这次记熟了
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        List<Integer> res = new ArrayList<>();
        for(int i=0;i<nums.length;i++){
                map.put(nums[i],i);
        }
        for(int i=0;i<nums.length;i++){
            int Rtarget = target-nums[i];
            if(map.containsKey(Rtarget)&&map.get(Rtarget)!=i){
                return new int[]{i,map.get(Rtarget)};
            }
        }
        return null;
    }
}
  • 12.20
    • get,containsKey
    • 最下面那个错了两个地方,一个是 nums 应该为 nums[i],第二个是需要判断不能是同一个数字
    • 答案更简洁,声明 hashmap 后没有先存数字,而是判断没有只有在在最后 put 进数字
    • 老子的笔记怎么没了!!!
class Solution {
    public int[] twoSum(int[] nums, int target) {
        // Key: 数值, Value: 索引
        Map<Integer, Integer> map = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            
            // 先检查我们要找的补数是否已经在 map 里了
            if (map.containsKey(complement)) {
                // 如果在,直接返回 [补数的索引, 当前索引]
                return new int[] { map.get(complement), i };
            }
            
            // 如果不在,把当前数字和索引存进去,供后面的数字查找
            map.put(nums[i], i);
        }
        return null;
    }
}
class Solution {自己理解的修正版本
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for(int i=0;i<nums.length;i++){
            int n = target-nums[i];
            if(map.containsKey(n)&&map.get(n)!=i){
                return new int[]{i,map.get(n)};
            }
        }
        return null;
 
    }
}
class Solution {错误版本
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map = new HashMap<>();
        for(int i=0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for(int i=0;i<nums.length;i++){
            int n = target-nums;
            if(map.contains(n)){
                return new int[]{i,map.getKey(n)};
            }
        }
        
    }
    return null;
}