Java Solution Easy to Understand


  • 0
    A
    public boolean checkSubarraySum(int[] nums, int k) {
            if(nums == null || nums.length == 0) return false;
    
            for (int i = 0; i < nums.length - 1; i++) {
                if (nums[i] == 0 && nums[i + 1] == 0) return true;
            }
            if(k == 0) return false;
            int n = nums.length;
            int[] dp = new int[n];
            dp[0] = nums[0];
            for(int i=1;i<n;i++) {
                dp[i] = dp[i-1] + nums[i];
                if(dp[i] % k == 0) return true;
            }
            int rem = 0;
            while(rem != n) {
                for(int i=rem+2;i<n;i++) {
                    dp[i] -= nums[rem];
                    if(dp[i] % k == 0) return true;
                }
                rem++;
            }
            return false;
        }

Log in to reply
 

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