1st round, 325 maxSubArrayLen
来源:互联网 发布:java jlabel 图片 编辑:程序博客网 时间:2024/06/05 17:14
public class Solution { public int maxSubArrayLen(int[] nums, int k) { if(nums==null || nums.length==0) return 0; Map<Integer, Integer> map= new HashMap<Integer, Integer>(); int sum=0; int len=0; for(int i=0; i<nums.length; i++){ sum+=nums[i]; if(sum==k) len=i+1; if(map.containsKey(sum-k)) len=Math.max(len, i-map.get(sum-k)); // this only works when len is 0; when the matching subarray is in the middle. NoNoNo, actually it is still useful when len=3, then subrray is from 4 to 10... if(!map.containsKey(sum)) map.put(sum, i); } return len; }}
这道题还蛮有意思的,通过HashMap来存放<sum, index>的对应关系,巧妙的把夹在中间的subrray [i, j]通过 [0, j] - [0, i] 来转换;要注意的一点是,当有相同的sum时候,是不需要存放这个entry的,因为是要求得max subarray的长度,那么起始点,就是要越小越好,如果有相同的sum,去更新的话,那么这个起点也更新且变大了
类似的题有,最小的subarrayLen 对应sum>=target,之后我会贴上来,在这个位置 [ waiting for link ] 更新一个链接到那一题。。
0 0
- 1st round, 325 maxSubArrayLen
- 1st round, 283 moveZeroes
- 1st round, 314 binaryTreeVerticalTraversal
- 1st round, 78 Subsets
- 1st round, 1 2Sum
- 1st round, 311 Sparse Matrix Multiplication
- 1st round, 67 Add Binary
- 1st round: 278 First Bad Version
- 1st round, 253 Meeting Rooms II
- 1st round, 91 Decode Ways
- 1st round, 15 3Sum
- 1st round, 277 Find the Celebrity
- 1st round, 200 number of isalnds
- 1st round, 161 One Edit Distance
- 1st round, 257 Binary Tree Paths
- 1st round, 494 Target Sum
- CSAPP 1st round Done & Src to start
- 1st round, 17 Letter Combinations of a Phone Number
- xss (跨站脚本攻击)教程
- Leetcode 202. Happy Number
- xss(跨站脚本攻击)教程
- 2016年总结:教师路的开启,爱情味的初尝 (下)
- 111. Minimum Depth of Binary Tree
- 1st round, 325 maxSubArrayLen
- 浅谈CSRF攻击方式
- 112. Path Sum
- 113. Path Sum II
- 114. Flatten Binary Tree to Linked List
- 115. Distinct Subsequences
- 116. Populating Next Right Pointers in Each Node
- 117. Populating Next Right Pointers in Each Node II
- 118. Pascal's Triangle