O(n) time O(k) space solution


  • 0
    S
        public boolean checkSubarraySum(int[] nums, int k) {
            Map<Integer, Integer> map = new HashMap<>();
            int len = nums.length, i;
            if (k == 0) {
                if (len > 1 && nums[0] == 0 && nums[1] == 0)
                    return true;
                return false;
            }
            int sum = 0;
            map.put(0, 1);
            
            for (i=0;i<len;i++) {
                sum = (sum + nums[i]) % k;
                Integer count = map.get(sum);
                
                if (count == null) 
                    map.put(sum, 1);
                else {
                    if (nums[i] % k != 0) {
                        return true;
                    } else if (count > 1)
                        return true;
                    else
                        map.put(sum, count + 1);
                }
            }
            return false;
        }
    }

  • 0
    O

    @sunzhihao
    [1, 1, 1, 0, 0, 0] and 0
    Your code will get the wrong result.


Log in to reply
 

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