525. 连续数组 (哈希表)

给定一个二进制数组, 找到含有相同数量的 0 和 1 的最长连续子数组(的长度)。

 

示例 1:

输入: [0,1]
输出: 2
说明: [0, 1] 是具有相同数量0和1的最长连续子数组。
示例 2:

输入: [0,1,0]
输出: 2
说明: [0, 1] (或 [1, 0]) 是具有相同数量0和1的最长连续子数组。
 

注意: 给定的二进制数组的长度不会超过50000。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/contiguous-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 //设置一个count 遇到1时 count+1 遇到0时 count-1
 4 //当count等于0时 代表从开头到现在 遇到的0和1的数量一样
 5 //当两个位置的count相同时 代表从这两个位置前一个位置 到这两个位置后一个位置 之间的0和1相等
 6 //用map记录count新值第一次出现的下标
 7 class Solution {
 8 public:
 9     int findMaxLength(vector<int>& nums) {
10         map<int, int> count_index_map;
11         count_index_map[0] = 0;
12         int count = 0;
13         int res = 0;
14         for (int i = 0; i < nums.size(); i++)
15         {
16             if (nums[i])count++;
17             else count--;
18             if (count_index_map.find(count) != count_index_map.end())
19                 res = max(res, i + 1 - count_index_map[count]);
20             else count_index_map[count] = i + 1;
21         }
22         return res;
23     }
24 };
25 int main()
26 {
27     int n;
28     int data;
29     vector<int> v;
30     cin >> n;
31     while (n--)
32     {
33         cin >> data;
34         v.push_back(data);
35     }
36     cout << Solution().findMaxLength(v);
37     return 0;
38 }

 

posted @ 2020-08-09 21:20  lancelee98  阅读(162)  评论(0编辑  收藏  举报