Java with a set


  • 0
    H
    public class Solution {
        public boolean checkSubarraySum(int[] nums, int k) {
             
            if(k==0){
                for(int i=1; i<nums.length; i++)
                    if(nums[i]==0 && nums[i-1]==0) return true;
                    return false;
            }
            
            Set<Integer> set = new HashSet<>(); // sum%k
            
            int sum = nums[0];
            sum%=k;
            set.add(0);
            set.add(sum);
        
            for(int i=1; i<nums.length; i++){
                sum += nums[i];
                sum%=k;
                if(set.contains(sum)) return true;
                set.add(sum);
            }
            return false;
        }
    }
    

Log in to reply
 

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