LeetCode 525. Contiguous Array

525. Contiguous Array

Description Submission Solutions

  • Total Accepted: 2476
  • Total Submissions: 8220
  • Difficulty: Medium
  • Contributors: bishwa 

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: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.

Example 2:

Input: [0,1,0]
Output: 2
Explanation: [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.

Subscribe to see which companies asked this question.


【题目分析】

这个题目的意思是给定一个只包含0,1的整数数组,找到数组中最长的一个子序列,该序列中1的个数和0的个数相同。


【思路】

这个题目真的很有意思啊,我感觉自己想不到这么好的解法。

看大家的解题思路如下:

The idea is to change 0 in the original array to -1. Thus, if we find SUM[i, j] == 0 then we know there are even number of -1 and 1 between index i and j. Also put the sum to index mapping to a HashMap to make search faster.


【java代码】

 1 public class Solution {
 2     public int findMaxLength(int[] nums) {
 3         for(int i = 0; i < nums.length; i++) {
 4             if(nums[i] == 0) nums[i] = -1;
 5         }
 6         
 7         int res = 0, sum = 0;
 8         Map<Integer, Integer> map = new HashMap<>();
 9         map.put(0, -1);
10         
11         for(int i = 0; i < nums.length; i++) {
12             sum += nums[i];
13             if(map.containsKey(sum)) {
14                 res = Math.max(res, i-map.get(sum));
15             }
16             else {
17                 map.put(sum, i);
18             }
19         }
20         
21         return res;
22     }
23 }

 

转载于:https://www.cnblogs.com/liujinhong/p/6472580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值