concise and readable java solution

  • 0

    need to optimize it to O(n) while space right now is minimum

    public boolean checkSubarraySum(int[] nums, int k) {
        if(nums==null) return false;
        int end = nums.length, sum=0;
        for(int i=0; i<nums.length; i++){ // iterate through whole the array, where subarray starts
            for(int j=i; j<end; j++){ // where subarray ends
                sum += nums[j]; 
                if(j-i>=1){  //only when length of subarray longer than 1 then it starts to judge
                    if(k!=0){ //normal case, k is not 0
                        if(sum%k==0) return true;
                    }else{ //corner case: when k is 0
                        if(sum==0) return true;  // only when k==0 && sum==0 return true
                        else return false;
            sum = 0;  //recompute the sum
        return false;

Log in to reply

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