0
点赞
收藏
分享

微信扫一扫

【LeeCode】523.连续的子数组和

辰鑫chenxin 2023-04-09 阅读 82

【题目描述】

给你一个整数数组 nums 和一个整数 k ,编写一个函数来判断该数组是否含有同时满足下述条件的连续子数组:

  • 子数组大小 至少为 2 ,且
  • 子数组元素总和为 k 的倍数。

如果存在,返回 true ;否则,返回 false 。

如果存在一个整数 n ,令整数 x 符合 x = n * k ,则称 x 是 k 的一个倍数。0 始终视为 k 的一个倍数。

https://leetcode.cn/problems/continuous-subarray-sum/

【示例】

【LeeCode】523.连续的子数组和_java

【代码】

package com.company;
import java.util.*;
// 2023-04-09

class Solution {
    public boolean checkSubarraySum(int[] nums, int k) {
        int len = nums.length;
        Map<Integer, Integer> map = new HashMap<>();
        map.put(0, 1);
        
        int presum = 0;
        for (int i = 0; i < len; i++){
            presum += nums[i];
            
            int key = k == 0 ? presum : presum % k;
            if (map.containsKey(key)){
                if (i - map.get(key) >= 2){
                    return true;
                }
                continue;
            }
            map.put(key, i);
        }
        return false;
    }
}

public class Test {
    public static void main(String[] args) {
        new Solution().checkSubarraySum(new int[] {23,2,4,6,7}, 6); // 输出:true
        new Solution().checkSubarraySum(new int[] {23,2,6,4,7}, 6); // 输出:true
        new Solution().checkSubarraySum(new int[] {23,2,6,4,7}, 13); //输出: false
    }
}

举报

相关推荐

0 条评论