当前位置: 首页 > article >正文

LeetCode75——Day17

文章目录

    • 一、题目
    • 二、题解

一、题目

1493. Longest Subarray of 1’s After Deleting One Element

Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1’s in the resulting array. Return 0 if there is no such subarray.

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1’s.
Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1’s is [1,1,1,1,1].
Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.

二、题解

遍历每个元素,求该元素删除后,左侧及右侧连续1的数目,并统计最大值。

注意初始化l和r的语句,若为1则不断+1,若为0则直接清0

class Solution {
public:
    int longestSubarray(vector<int>& nums) {
        int n = nums.size();
        if(n == 1) return 0;
        //元素左侧1的个数
        vector<int> l(n,0);
        //元素右侧1的个数
        vector<int> r(n,0);
        l[0] = nums[0];
        r[n-1] = nums[n-1];
        for(int i = 1;i < n;i++){
            l[i] = (l[i-1] + 1) * nums[i];
        }
        for(int i = n - 2;i >= 0;i--){
            r[i] = (r[i+1] + 1) * nums[i];
        }
        int res = 0;
        for(int i = 0;i < n;i++){
            if(i == 0) res = max(res,r[i+1]);
            else if(i > 0 && i < n - 1) res = max(res,l[i-1] + r[i+1]);
            else res = max(res,l[i-1]);
        }
        return res;
    }
};

http://www.kler.cn/a/105581.html

相关文章:

  • 矢量图形编辑软件Illustrator 2023 mac中文版软件特点(ai2023) v27.9
  • 太烂的牌也要打完只为自己也不是为了其他什么原因。
  • 腾讯云国际站服务器端口开放失败怎么办?
  • Java零基础入门-逻辑运算符
  • 第七节——Vue中定义组件状态驱动视图
  • 25期代码随想录算法训练营第二天 | 977.有序数组的平方 ,209.长度最小的子数组 ,59.螺旋矩阵II
  • 多线程---创建线程的七种方式
  • 自动化测试系列 —— UI自动化测试
  • 用图说话——流程图进阶
  • Python字典-dict “ “ ---记一次查缺补漏“ “
  • CMake教程-第 10 步:选择静态或共享库
  • LSKA(大可分离核注意力):重新思考CNN大核注意力设计
  • 鸿运主动安全监控云平台任意文件下载漏洞复现 [附POC]
  • postgis ST_CoverageInvalidEdges使用说明
  • 软考高级系统架构设计师系列之:案例分析典型试题四
  • [论文阅读]MVF——基于 LiDAR 点云的 3D 目标检测的端到端多视图融合
  • Java中会出现内存泄漏吗
  • 用汇编来理解堆栈
  • 力扣第406题 根据身高重建队列 c++ 贪心思维
  • CGAL 5.6 - Halfedge Data Structures