博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Leetcode: Maximum Size Subarray Sum Equals k
阅读量:6291 次
发布时间:2019-06-22

本文共 1388 字,大约阅读时间需要 4 分钟。

Given an array nums and a target value k, find the maximum length of a subarray that sums to k. If there isn't one, return 0 instead.Example 1:Given nums = [1, -1, 5, -2, 3], k = 3,return 4. (because the subarray [1, -1, 5, -2] sums to 3 and is the longest)Example 2:Given nums = [-2, -1, 2, 1], k = 1,return 2. (because the subarray [-1, 2] sums to 1 and is the longest)Follow Up:Can you do it in O(n) time?

Like the other subarray sum problems

Use a HashMap to keep track of the sum from index 0 to index i, use it as the key, and use the current index as the value

build the hashmap: scan from left to write, if the current sum does not exist in the hashmap, put it in. If the current sum does exist in Hashmap, do not replace or add to the older value, simply do not update. Because this value might be the left index of our subarray in later comparison. We are looking for the longest subarray so we want the left index to be the smaller the better. 

Every time we read a number in the array, we check to see if map.containsKey(num-k), if yes, try to update the maxLen.

1 public class Solution { 2     public int maxSubArrayLen(int[] nums, int k) { 3         if (nums==null || nums.length==0) return 0; 4         HashMap
map = new HashMap
(); 5 map.put(0, -1); 6 int sum = 0; 7 int maxLen = Integer.MIN_VALUE; 8 for (int i=0; i

 

转载地址:http://hjcta.baihongyu.com/

你可能感兴趣的文章
闲扯下午引爆乌云社区“盗窃”乌云币事件
查看>>
02@在类的头文件中尽量少引入其他头文件
查看>>
JAVA IO BIO NIO AIO
查看>>
input checkbox 复选框大小修改
查看>>
BOOT.INI文件参数
查看>>
vmstat详解
查看>>
新年第一镖
查看>>
unbtu使用笔记
查看>>
OEA 中 WPF 树型表格虚拟化设计方案
查看>>
Android程序开发初级教程(一) 开始 Hello Android
查看>>
使用Gradle打RPM包
查看>>
“我意识到”的意义
查看>>
淘宝天猫上新辅助工具-新品填表
查看>>
再学 GDI+[43]: 文本输出 - 获取已安装的字体列表
查看>>
nginx反向代理
查看>>
操作系统真实的虚拟内存是什么样的(一)
查看>>
hadoop、hbase、zookeeper集群搭建
查看>>
python中一切皆对象------类的基础(五)
查看>>
modprobe
查看>>
android中用ExpandableListView实现三级扩展列表
查看>>