[LintCode] 1844. subarray sum equals to k II

Given an array of integers and an integer k, you need to find the minimum size of continuous no-empty subarrays whose sum equals to k, and return its length.

if there are no such subarray, return -1.

Example1

Input: 
nums = [1,1,1,2] and k = 3
Output: 
2

Example2

Input: 
nums = [2,1,-1,4,2,-3] and k = 3
Output: 
2

子数组和为K II。

给定一个整数数组和一个整数k,你需要找到和为k的最短非空子数组,并返回它的长度。

如果没有这样的子数组,返回-1.

这道题的思路是前缀和。一般找一个符合题意的子数组,前缀和会是一个比较好用的思路。这里我们创建一个 hashmap,记录的是<数组的前缀和, 当前 index>,也就是说我们记录每一个 unique 的前缀和以及出现这个前缀和的位置。当我们遇到一个前缀和 = sum - k,同时这个前缀和存在于 hashmap 的时候,我们就找到了一个数组和为 K 的子数组。我们不断去找这样的子数组,返回最短的长度。

时间O(n)

空间O(n)

Java实现

 1 public class Solution {
 2     public int subarraySumEqualsKII(int[] nums, int k) {
 3         // write your code here
 4         int len = nums.length;
 5         HashMap<Integer, Integer> map = new HashMap<>();
 6         map.put(0, -1);
 7         int sum = 0;
 8         int res = Integer.MAX_VALUE;
 9         for (int i = 0; i < len; i++) {
10             sum += nums[i];
11             if (map.containsKey(sum - k)) {
12                 res = Math.min(res, i - map.get(sum - k));
13             }
14             map.put(sum, i);
15         }
16         return res == Integer.MAX_VALUE ? -1 : res;
17     }
18 }

 

LeetCode 题目总结

posted @ 2022-06-23 04:27  CNoodle  阅读(198)  评论(0编辑  收藏  举报