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

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.lryc.cn/news/207725.html

相关文章:

  • Spring中Bean的作用域
  • 什么是命令行参数解析和选项处理?
  • 网络协议--TFTP:简单文件传送协议
  • MongoDB 的集群架构与设计
  • volatile 系列之实现原理
  • 【黑马程序员】mysql进阶篇笔记
  • A - Block Sequence
  • 0031【Edabit ★☆☆☆☆☆】【使用箭头函数】Using Arrow Functions
  • C#,数值计算——分类与推理,基座向量机(SVM,Support Vector Machines)的计算方法与源程序
  • 面试总结之消息中间件
  • Java零基础入门-逻辑运算符
  • 图的应用3.0-----拓扑排序
  • Unity之ShaderGraph如何实现冰冻效果
  • 解决 viteprees 中 vp-doc 内置样式影响组件预
  • flask 和fastdeploy 快速部署 yolov3
  • Go 反射
  • 竞赛选题 深度学习卷积神经网络垃圾分类系统 - 深度学习 神经网络 图像识别 垃圾分类 算法 小程序
  • ts-node模块
  • 【VUE】ElementPlus之动态主题色调切换(Vue3 + Element Plus+Scss + Pinia)
  • MySQL数据库基本操作1
  • Webpack简介及打包演示
  • 面向对象设计模式——命令模式
  • selenium测试框架快速搭建(ui自动化测试)
  • TypeScript中的类型映射
  • 系统平台同一网络下不同设备及进程数据通讯--DDS数据分发服务中间件
  • golang小技巧
  • JavaWeb——IDEA操作:Project最终新建module
  • 前端开发技术栈(工具篇):2023深入了解webpack的安装和使用以及核心概念和启动流程(详细) 63.3k stars
  • [SQL开发笔记]LIKE操作符:在 WHERE 子句中搜索列中的指定模式
  • flutter深研