当前位置:网站首页>LeetCode_ Prefix and_ Hash table_ Medium_ 525. Continuous array
LeetCode_ Prefix and_ Hash table_ Medium_ 525. Continuous array
2022-07-26 15:26:00 【Old street of small town】
1. subject
Given a binary array nums , Find the same number of 0 and 1 The longest continuous subarray of , And returns the length of the subarray .
Example 1:
Input : nums = [0,1]
Output : 2
explain : [0, 1] It's the same number 0 and 1 The longest continuous subarray of .
Example 2:
Input : nums = [0,1,0]
Output : 2
explain : [0, 1] ( or [1, 0]) It's the same number 0 and 1 The longest continuous subarray of .
Tips :
1 <= nums.length <= 105
nums[i] No 0 Namely 1
source : Power button (LeetCode)
link :https://leetcode.cn/problems/contiguous-array
2. Ideas
(1) The prefix and
The general idea is to use prefixes and arrays , namely preSum[i] preservation nums[0…i - 1] And , Then use two more layers for Loop through the sub array that meets the condition of the topic , If you qualify , Update res, Otherwise, continue to traverse . After traversal, return directly to res that will do . But in LeetCode When submitting on “ Time limit exceeded ” A hint of ! This shows the method ( The time complexity is O(n2)) Still need to be optimized , See ideas for specific optimization methods 2.
(2) The prefix and & Hashtable
Train of thought reference The LeetCode User questions .
① Right way of thinking 1 Initialize array in code preSum Make a change to the operation of , Use preSum[i] To record nums[0…i - 1] The elements in 0 And elements 1 The difference in the number of :
preSum[i] = preSum[i - 1] + (nums[i - 1] == 1 ? 1 : -1);
obviously , We can know :
When preSum[i] > 0 when ,preSum[i] Express nums[0…i - 1] in 1 Than 0 More numbers ;
When preSum[i] < 0 when ,|preSum[i]| Express nums[0…i - 1] in 1 Than 0 A small number ;
When preSum[i] = 0 when ,nums[0…i - 1] in 0 and 1 The number of is equal ;
② Define hash table hashMap, To hold preSum[i] And its corresponding subscript i;
③ Because the length of the sub array that meets the conditions of the topic is at least 2, So it's traversing preSum Time subscript 2 Start . In the process of traversing , use hashMap Save in a sub array 0、1 The minimum subscript of the number of element differences , In the following code :
if (!hashMap.containsKey(preSum[i - 2])) {
hashMap.put(preSum[i - 2], i - 2);
}
④ Also judge preSum[i] Does it exist in hashMap in , If there is , Then set the subscript position appearing before as preIdx = hashMap.get(preSum[i]),
So the corresponding nums[0…preIdx - 1] Medium element 0 And elements 1 The number of differences is k, for example [0, 1, 1, 1],k = 2,preIdx = 4
At the same time, we can also know nums[0…i - 1] Medium element 0 And elements 1 The number of differences is also k, for example [0, 1, 1, 1, 0, 1],k = 2,i = 6
So at this time nums[preIdx…i - 1] Medium element 0 And elements 1 The number of must be equal , That is, the sub array that meets the conditions is [0, 1], The corresponding length is i - preIdx, Update at this time res that will do .
The derivation process is also relatively simple :
from preSum[i] = k -> nums[0...i - 1] Medium element 0 And elements 1 The number of differences is k,
from preSum[preIdx] = k -> nums[0...preIdx - 1] Medium element 0 And elements 1 The number of differences is k, And preIdx < i
because nums[0...preIdx - 1] contain nums[0...i - 1], So clearly nums[0...preIdx - 1] Medium element 0 And elements 1 The number difference is k The interval of is just right
yes nums[0...i - 1], So the remaining interval nums[preIdx...i - 1] Medium element 0 And elements 1 The number of must be equal .
3. Code implementation (Java)
// Ideas 1———— The prefix and
class Solution {
public int findMaxLength(int[] nums) {
int res = 0;
int length = nums.length;
int[] preSum = new int[length + 1];
for (int i = 1; i < length + 1; i++) {
preSum[i] = preSum[i - 1] + nums[i - 1];
}
for (int i = 0; i < length - 1; i++) {
for (int j = i + 2; j < length + 1; j += 2) {
int sum_ij = preSum[j] - preSum[i];
if (sum_ij != 0 && (j - i) / sum_ij == 2 && (j - i) % sum_ij == 0) {
res = Math.max(res, j - i);
}
}
}
return res;
}
}
// Ideas 2———— The prefix and & Hashtable
class Solution {
public static int findMaxLength(int[] nums) {
int res = 0;
int length = nums.length;
int[] preSum = new int[length + 1];
for (int i = 1; i < length + 1; i++) {
preSum[i] = preSum[i - 1] + (nums[i - 1] == 1 ? 1 : -1);
}
Map<Integer, Integer> hashMap = new HashMap<>();
for (int i = 2; i <= length; i++) {
if (!hashMap.containsKey(preSum[i - 2])) {
hashMap.put(preSum[i - 2], i - 2);
}
if (hashMap.containsKey(preSum[i])) {
int preIdx = hashMap.get(preSum[i]);
res = Math.max(res, i - preIdx);
}
}
return res;
}
}
边栏推荐
- 兆骑科创高端人才项目引进落地,双创大赛承办,线上直播路演
- How to write the format of a university thesis?
- How to find undergraduate dissertations of domestic universities?
- Strengthen the defense line of ecological security, and carry out emergency drills for environmental emergencies in Guangzhou
- Database expansion can also be so smooth, MySQL 100 billion level data production environment expansion practice
- 【基础】动态链接库/静态链接库的区别
- 使用两个栈实现一个队列
- 如何将规划图转成带经纬度的矢量数据geojson
- 什么是传输层协议TCP/UDP???
- Deep packet inspection using cuckoo filter paper summary
猜你喜欢

anaconda No module named ‘cv2‘

Enterprise digital transformation needs in-depth research, and it cannot be transformed for the sake of transformation

FOC motor control foundation

cs224w(图机器学习)2021冬季课程学习笔记5

什么是传输层协议TCP/UDP???

Prometheus adds redis and MySQL node monitoring

If food manufacturing enterprises want to realize intelligent and collaborative supplier management, it is enough to choose SRM supplier system

固态硬盘对游戏运行的帮助有多少

信用卡数字识别(opencv,代码分析)

Deep Packet Inspection Using Cuckoo Filter论文总结
随机推荐
谷歌尝试为ChromeOS引入密码强度指示器以提升线上安全性
Prometheus adds email alarm and enterprise wechat robot alarm
Practical purchasing skills, purchasing methods of five bottleneck materials
R语言使用lattice包中的histogram函数可视化直方图(histogram plot)、col参数自定义填充色、type参数自定义直方图显示模式(计数或者比例)
What is the transport layer protocol tcp/udp???
R语言使用lm函数构建多元回归模型(Multiple Linear Regression)、并根据模型系数写出回归方程、使用fitted函数计算出模型的拟合的y值(响应值)向量
R语言检验相关性系数的显著性:使用cor.test函数计算相关性系数的值和置信区间及其统计显著性(如果变量来自正态分布总体使用皮尔森方法pearson)
2023 catering industry exhibition, China catering supply chain exhibition and Jiangxi catering Ingredients Exhibition were held in February
Chuhuan technology is listed on Shenzhen Stock Exchange: Minsheng securities, with a market value of 2.7 billion, is a shareholder
R language ggplot2 visualization: use the ggdotplot function of ggpubr package to visualize dot plot, set the add parameter to add the mean and standard deviation vertical lines, and set the error.plo
【LeetCode每日一题】——268.丢失的数字
sqlDeveloper工具快速入门
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
【静态代码质量分析工具】上海道宁为您带来SonarSource/SonarQube下载、试用、教程
OpenGL学习日记2——着色器
Cs224w (Figure machine learning) 2021 winter course learning notes 5
How to query foreign literature?
数商云:引领化工业态数字升级,看摩贝如何快速打通全场景互融互通
企业数字化转型需要深入研究,不能为了转型而转型
C# 给Word每一页设置不同文字水印