Contiguous Array
来源:互联网 发布:眼睛变大知乎 编辑:程序博客网 时间:2024/05/22 17:30
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]Output: 2Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]Output: 2Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
Note: The length of the given binary array will not exceed 50,000.
比较巧妙的一道题,正常写的话会TLE,参考答案的思路是,设置一个计数,如果遇到1,则+1, 遇到0, 则-1。这样的话会有这种结论:当出现两个index他们的值相等的时候,说明,他们之间的1的个数刚好等于0的个数。
代码:
public int findMaxLength2(int[] nums) { if(nums == null || nums.length == 0) return 0; HashMap<Integer, Integer> map = new HashMap<>(); int count = 0; map.put(0, 0); for(int i=0;i<nums.length;i++) { if(nums[i] == 1) { count++; } map.put(i+1, count); } int length = nums.length; while(length>0) { if(length % 2 != 0) { length--;continue; } for(int i=0;i<=nums.length-length;i++) { if((map.get(i+length) - map.get(i)) == (length/2)) { // 这里减法不用+1, 因为就是算的差的部分的长度 return length; } } length-=2; } return 0; }
这里的i 理解为: 在i之前的部分的和。
public int findMaxLength(int[] nums) { if(nums == null || nums.length == 0) return 0; HashMap<Integer, Integer> map = new HashMap<>(); map.put(0, 0);//index = -1, value = 0 int count = 0; int maxLength = 0; for(int i=0;i<nums.length;i++) { count += nums[i] == 1 ? 1: -1; if(map.containsKey(count)) { maxLength = Math.max(maxLength, i+1 - map.get(count)); } else { map.put(count, i+1); } } return maxLength; }
阅读全文
0 0
- Contiguous Array
- Contiguous Array
- LeetCode 525. Contiguous Array
- Leetcode 525. Contiguous Array
- 525. Contiguous Array
- 525. Contiguous Array
- 525. Contiguous Array
- [LeetCode]525. Contiguous Array
- 525. Contiguous Array Medium
- 525. Contiguous Array
- 525. Contiguous Array
- [leetcode] 525. Contiguous Array
- [leetcode]525. Contiguous Array
- [leetcode525]Contiguous Array
- 525. Contiguous Array
- 525. Contiguous Array
- LeetCode 525. Contiguous Array
- 525. Contiguous Array 题解
- 【python】京东价格监控——自行设置商品,降价邮件提醒
- mysql添加数据库
- Spring05---静态代理
- Spring06---动态代理
- 浏览器的标准模式和怪异模式
- Contiguous Array
- Android studio 百度地图开发(10)语音播报的问题:能正常导航,但是无法语音播报
- 05-1 JS的DOM
- how to fix "Cannot find a valid baseurl for repo: poptop-stable/7" in centos 7 *64 when use "yum -y
- 在CentOS上搭建PHP服务器环境
- How to get the SHA-1 fingerprint certificate in Android Studio for debug mode?
- java.lang.ClassNotFoundException: com.sun.faces.config.ConfigureListener
- Solve the Equation
- Android百度地图实例详解之仿摩拜单车APP(包括附近车辆、规划路径、行驶距离、行驶轨迹记录,导航等)