Nested if and &&?? Java HashMap


  • 0
    K

    First, the test case is

    [1,0,1,1]
    1

    expected answer: true

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
          int len = nums.length;      
          HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
          for(int i = 0; i < len; i++){
              if(m.containsKey(nums[i])){
                  if((i - m.get(nums[i])) <= k) return true;
              }
              else m.put(nums[i],i);
          }
          return false;
        }
    }
    

    I wrote the above code but the result is false.
    But then I change the nested if clause to if( && ) as below

    public class Solution {
        public boolean containsNearbyDuplicate(int[] nums, int k) {
          int len = nums.length;
          HashMap<Integer,Integer> m = new HashMap<Integer,Integer>();
          for(int i = 0; i < len; i++){
              if(m.containsKey(nums[i]) && (i - m.get(nums[i])) <= k){
                   return true;
              }
              else m.put(nums[i],i);
          }
          return false;
        }
    }
    

    Now it gives the right answer and pass the OJ.

    I'm confused...


  • 2
    H
          if(m.containsKey(nums[i])){
              if((i - m.get(nums[i])) <= k) return true;
          }
          else m.put(nums[i],i);
    

    the logic is difference, if the statement m.containsKey(nums[i]) is true while statement if((i - m.get(nums[i])) <= k) is false, the program won't execute m.put(nums[i],i); that's the difference with

          if(m.containsKey(nums[i]) && (i - m.get(nums[i])) <= k){
               return true;
          }
          else m.put(nums[i],i);
    

  • 0
    K

    I see. I missed one point, which is if i - m.get(nums[i])) > k, we need to put it into the map. Thanks~


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.