zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    二维卷积层
    gluon 实现多层感知机MLP分类FashionMNIST
    gluon实现softmax分类FashionMNIST
    gluon 实现线性回归
    GPU使用
    Python迭代器和生成器
    L2范数惩罚项,高维线性回归
    多项式拟合
    模型选择,欠拟合,过拟合
    多层感知机MLP的gluon版分类minist
  • 原文地址:https://www.cnblogs.com/lancelee98/p/13466430.html
Copyright © 2011-2022 走看看