Leetcode 974 和可被K整除的子数组】的更多相关文章

题目: 解法 //前缀和算法+hash表 class Solution { public: int subarraysDivByK(vector<int>& A, int K) { int res=0; int sum=0; unordered_map<int,int> hash = {{0,1}};//考虑自身被整除的情况,神操作,合并了自身被整除和不被整除两种情况 for(int num:A){ sum += num; int module = (sum % K + K…
974. 和可被 K 整除的子数组 知识点:数组:前缀和: 题目描述 给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续.非空)子数组的数目. 示例 输入:A = [4,5,0,-2,-3,1], K = 5 输出:7 解释: 有 7 个子数组满足其元素之和可被 K = 5 整除: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3]. 解法一:前缀和 连续子数组,又带有和-->前缀和…
题目 给定一个整数数组 A,返回其中元素之和可被 K 整除的(连续.非空)子数组的数目. 示例: 输入:A = [4,5,0,-2,-3,1], K = 5 输出:7 解释: 有 7 个子数组满足其元素之和可被 K = 5 整除: [4, 5, 0, -2, -3, 1], [5], [5, 0], [5, 0, -2, -3], [0], [0, -2, -3], [-2, -3] 前缀和+HashMap 常规思路是:首先求得前缀和数组,然后检查每一个子数组的和是否能被K整除.这样做的时间复杂…
862. 和至少为 K 的最短子数组 知识点:单调:队列:前缀和 题目描述 返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K . 如果没有和至少为 K 的非空子数组,返回 -1 . 示例 输入:A = [1], K = 1 输出:1 输入:A = [1,2], K = 4 输出:-1 输入:A = [2,-1,2], K = 3 输出:3 解法一:单调队列+前缀和 这个题目是求连续子数组,所以自然可以想到前缀和,也就是用一个数组统计到第i个位置的前缀和.所以问题就变成了 j>i &am…
Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. E…
返回 A 的最短的非空连续子数组的长度,该子数组的和至少为 K 如果没有和至少为 K 的非空子数组,返回 -1 . 示例 1: 输入:A = [1], K = 1 输出:1 示例 2: 输入:A = [1,2], K = 4 输出:-1 示例 3: 输入:A = [2,-1,2], K = 3 输出:3 1 <= A.length <= 50000 -10 ^ 5 <= A[i] <= 10 ^ 5 1 <= K <= 10 ^ 9 这道题的关键在于我们要知道各个区间的…
public class Solution { public int subarraySum(int[] nums, int k) { int count = 0, pre = 0; HashMap < Integer, Integer > map = new HashMap < > (); map.put(0, 1); for (int i = 0; i < nums.length; i++) { pre += nums[i]; if (mp.containsKey(pre…
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies: Si % Sj = 0 or Sj % Si = 0. If there are multiple solutions, return any subset is fine. Example 1: nums: [1,2,3] Re…
Return the length of the shortest, non-empty, contiguous subarray of A with sum at least K. If there is no non-empty subarray with sum at least K, return -1. Example 1: Input: A = [1], K = 1 Output: 1 Example 2: Input: A = [1,2], K = 4 Output: -1 Exa…
给定一个长度为n的数组a,它有n(n+1)/2​​个子数组.请计算这些子数组的和,然后按照升序排列,并返回排序后第k个数. 1≤n≤10​^5 1≤a​i≤10^​9 1≤k≤​n(n+1)/2 在线评测地址:点击此处前往 Example1 Input: [2,3,1,4] 6 Output:5 Explanation: 我们可以得到所有子数组的和是 [1,2,3,4,4(3 + 1), 5(1 + 4), 5(2 + 3), 6(2 + 3 + 1), 8(3 + 1 + 4), 10(2 +…