523. Continuous Subarray Sum ( if the array has a continuous subarray of size at least 2 that sums up to the multiple of k or k )

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
      // prefix sum mod k
      int[] preprocess = new int[nums.length + 1];
      preprocess[0] = 0;
      for(int i = 1; i <= nums.length; i++){
        if (k == 0){
            return false;
        }else{
            preprocess[i] = (preprocess[i-1] + nums[i-1]) % k;
        }
      }
      
      
      HashMap<Integer, Integer> map = new HashMap<>();
      for(int i = 0; i < preprocess.length; i++){
        if(!map.containsKey(preprocess[i])){
          map.put(preprocess[i], i);
        }else{
          int index = map.get(preprocess[i]);
          if( i - index >= 1){
            return true;
          }
        }
      }
      return false;
    }
}

 (找到连续的 subarray 和等于 k (不需要 k 的倍数)

https://github.com/tongzhang1994/Facebook-Interview-Coding/blob/master/Subarray%20Sum.java

 

// 1 2 3 
//  0 1 3 6 
// sum = 6 true 6 - 6 = 0. 0 is in the prefix 
// sum = 5 true 6 - 5 = 1 . 1 is in the prefix 

public boolean checkSubarraySum(int[] nums, int k){
  // preprocess the prefix sum 
  int[] prefix = new int[nums.length + 1];
  prefix[0] = 0;
  for(int i = 1; i < nums.length; i++){
    prefix[i] = prefix[i - 1] + nums[i - 1];
  }
  
  // traverse the prefix sum and see if the subarray 
  // sum is in the array
  HashMap<Integer, Integer> map = new HashMap<>();
  for(int i = 0; i < prefix.length; i++){
    if(!map.containsKey(prefix[i])){
      map.put(prefix[i], i);
    }
       
    if(map.containsKey(prefix[i] - k)){
      return true;
    }
  }
  return false;
}

 

Given a list of non-negative numbers and a target integer k, write a function to check if the array has a continuous subarray of size at least 2 that sums up to the multiple of k, that is, sums up to n*k where n is also an integer.

Example 1:

Input: [23, 2, 4, 6, 7],  k=6
Output: True
Explanation: Because [2, 4] is a continuous subarray of size 2 and sums up to 6.

 

Example 2:

Input: [23, 2, 6, 4, 7],  k=6
Output: True
Explanation: Because [23, 2, 6, 4, 7] is an continuous subarray of size 5 and sums up to 42.

 

Note:

  1. The length of the array won't exceed 10,000.
  2. You may assume the sum of all the numbers is in the range of a signed 32-bit integer.

posted on 2018-07-18 09:05  猪猪&#128055;  阅读(154)  评论(0)    收藏  举报

导航