Problem
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:
The length of the array won"t exceed 10,000.
You may assume the sum of all the numbers is in the range of a signed 32-bit integer.
class Solution { public boolean checkSubarraySum(int[] nums, int k) { if (nums == null || nums.length < 2) return false; if (k == 0) { for (int i = 0; i < nums.length-1; i++) { if (nums[i] == 0 && nums[i+1] == 0) return true; } return false; } Mapmap = new HashMap<>(); int sum = 0; map.put(0, -1); for (int i = 0; i < nums.length; i++) { sum += nums[i]; sum %= k; if (map.containsKey(sum)) { if (i-map.get(sum) > 1) return true; } else { map.put(sum, i); } } return false; } }
文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。
转载请注明本文地址:https://www.ucloud.cn/yun/72296.html
Problem Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. Example 1: Input:nums = [1,1,1], k = 2 Output: 2 Note:The length o...
摘要:前言从开始写相关的博客到现在也蛮多篇了。而且当时也没有按顺序写现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。顺序整理更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新更新 前言 从开始写leetcode相关的博客到现在也蛮多篇了。而且当时也没有按顺序写~现在翻起来觉得蛮乱的。可能大家看着也非常不方便。所以在这里做个索引嘻嘻。 顺序整理 1~50 1...
摘要:在线网站地址我的微信公众号完整题目列表从年月日起,每天更新一题,顺序从易到难,目前已更新个题。这是项目地址欢迎一起交流学习。 这篇文章记录我练习的 LeetCode 题目,语言 JavaScript。 在线网站:https://cattle.w3fun.com GitHub 地址:https://github.com/swpuLeo/ca...我的微信公众号: showImg(htt...
Problem Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isnt one, return 0 instead. Note The sum of the entire nums array is guaranteed to fit ...
Problem Find the contiguous subarray within an array (containing at least one number) which has the largest sum. Example For example, given the array [-2,1,-3,4,-1,2,1,-5,4],the contiguous subarray [4...
阅读 702·2023-04-25 17:54
阅读 2944·2021-11-18 10:02
阅读 1115·2021-09-28 09:35
阅读 625·2021-09-22 15:18
阅读 2820·2021-09-03 10:49
阅读 2995·2021-08-10 09:42
阅读 2546·2019-08-29 16:24
阅读 1235·2019-08-29 15:08