zoukankan      html  css  js  c++  java
  • 525.连续数组 力扣 (前缀和)

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

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

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

    题解:求前缀和,计算和相同的两个,最远的距离,也就是记录一下某个和最早出现的位置。
    题源:https://leetcode-cn.com/problems/contiguous-array/
    class Solution {
    public:
        int findMaxLength(vector<int>& nums) {
          int l=nums.size();
          int sum=0;
          int res=0;
          map<int,int> mp;
          mp[0]=-1;
          for(int i=0;i<l;i++)
          {
              if (nums[i]==1) sum++;
                 else sum--;
              if(mp.find(sum)!=mp.end())  res=max(res,i-mp[sum]);
                 else mp[sum]=i;
          }
          return res;
        }
    };


  • 相关阅读:
    Apple Tree(树状数组+线段树)
    平衡阵容(RMQ st表算法)
    一起去打CS
    夜归

    淋雨
    大马戏
    雨中行船
    弄堂里
    夜游天安门
  • 原文地址:https://www.cnblogs.com/stepping/p/14845274.html
Copyright © 2011-2022 走看看