This problem requires add continues numbers, so the best solution is using prefix sum. Time complexity: O(n).

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, -1);
        int sum =0;
        for(int i=0;i<nums.length;i++){
            sum+=nums[i];
            int rest = sum%k;
            if(map.containsKey(rest)){
                int index = map.get(rest);
                if(i-index>=2)
                    return true;
            }
            else 
                map.put(rest, i);  //ony when map doesn't contain rest, put rest, otherwise don't update rest's index
        }
        return false;
    }
}

 

posted on 2022-02-25 10:42  阳光明媚的菲越  阅读(11)  评论(0编辑  收藏  举报