Easy Understanding Java Solution with HashMap


  • 1
    W

    map.put(0, -1) means there is non element in a array so far.

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

Log in to reply
 

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