当前位置:网站首页>LeetCode41——First Missing Positive——hashing in place & swap
LeetCode41——First Missing Positive——hashing in place & swap
2022-07-06 09:02:00 【Zheyuan Zou】
This problem lets us find the missing first element in an array , That is to say The smallest positive number , The questions are as follows :
In fact, it is not difficult to realize this function , The difficulty lies in the problem of the algorithm Time and space complexity make constraints at the same time , That is, the complexity of time is O ( n ) O(n) O(n), At the same time, the spatial complexity is O ( 1 ) O(1) O(1).
Before finishing this problem , One very important observation is :
For length is N Array of nums, The minimum missing positive number will only be in the interval [ 1 , N + 1 ] [1, N + 1] [1,N+1] Inside , in other words , The length is N The array of will only occupy [ 1 , N ] [1,N] [1,N] this N A positive integer , So that the first missing positive integer is N+1. Other special cases include the presence of greater than in the array N The positive integer , Or non positive integer (<=0 Number of numbers ), Will make the smallest missing positive integer fall in [ 1 , N ] [1,N] [1,N] In this range , This conclusion is the premise to complete this problem .
Time complexity and space complexity are both O ( n ) O(n) O(n) The algorithm of can be Apply for a length of n Array of Flag Express [ 1 , N ] [1,N] [1,N], For convenience, I take one more element here , Then mark one by one in nums The elements that appear in , Then look at the first positive number that doesn't appear . The code is as follows :
int firstMissingPositive(vector<int>& nums) {
/*O(n)-O(n) algorithm*/
/*apply for a flag array to record existing element*/
bool* Flag = new bool [nums.size() + 1];
for(int i = 0 ; i <= nums.size() ; ++i)
Flag[i] = false;
/*set flag[nums[i]] as true when nums[i]∈[1, N]*/
size_t Size = nums.size();
int Result = Size + 1;
for(int i = 0 ; i < nums.size() ; ++i)
if(nums[i] > 0 && nums[i] <= Size)
Flag[nums[i]] = true;
/*search for the first missing positive number*/
for(int i = 1 ; i <= nums.size() ; ++i)
if(!Flag[i])
{
Result = i;
break;
}
delete [] Flag;
return Result;
}
This simple way increases the spatial complexity , Reduced time complexity , Just traverse 2 The number group is ok . However, it still fails to meet the requirements of the topic while taking into account the time complexity and space complexity , Here you are The two methods To achieve this goal ( Learned from the official explanation , cry :(:
One 、 In place hash (hashing in place)
This way is mainly in the original nums Array [ 1 , N ] [1,N] [1,N] The tag , This algorithm is divided into the following steps :
- Traverse nums for the first time , Will the Less than or equal to 0 All elements of are modified to N+1,N It's array length . This is because Later, you need to subtract... From the elements in the array 1 Mark as a subscript nums The elements in . Negative numbers and 0 subtract 1 Then the index value will become negative . Modified into N+1 Then it will eliminate this problem , and N+1-1 = N, It will not be marked nums Any element in (nums The maximum available index is N-1).
- Traverse nums The second time , take nums Array Between the range [ 1 , N ] [1,N] [1,N] Subtract 1 As a subscript , Set the element corresponding to the subscript to a negative number to indicate that this element exists .
- Traverse nums third time , Look at the first positive integer that appears in nums Which one of them , Let's say the number one in the array is i Bits are positive , that Indicates the positive number corresponding to this index i+1 Never had . Assume negative numbers , So the first positive number that doesn't appear is N+1.
The following is the source code of the implementation :
int firstMissingPositive(vector<int>& nums) {
int Size = nums.size();
/*Iteration 1*/
for(int i = 0 ; i < Size ; ++i)
if(nums[i] <= 0)
nums[i] = Size + 1;
/*Iteration 2*/
for(int i = 0 ; i < Size ; ++i)
{
int num = abs(nums[i]); // num must be larger than 0
if(num <= Size) // make sure the num is less than N
nums[num - 1] = -abs(nums[num - 1]); // make sure the value is negative
}
/*Iteration 3*/
for(int i = 0 ; i < Size ; ++i)
if(nums[i] > 0)
return i + 1;
return Size + 1;
}
Two 、 Local exchange (swap)
This algorithm is simpler than local hash , Its core idea is to put every element into it “ belong ” The location of . say concretely , One is worth x ∈ [ 1 , N ] x \in [1,N] x∈[1,N] The elements of , It should be indexed x-1 The location of , We just need Swap it with the element where it should be that will do .
But note that this exchange is not It was done in one stroke , The newly replaced element also needs to be arranged in the position it should be , So this is a The logic of the cycle . Finally, there is a special case that needs to be discussed , That's it If the two elements exchanged are the same , You're going to fall into a dead circle ( The two elements are constantly changing ), Therefore, the discussion and avoidance of this situation should be added to the conditions of circulation .
One last check nums Array , The first element that appears where it should not appear Is the smallest positive number missing .
The overall code is as follows :
int firstMissingPositive(vector<int>& nums) {
int Size = nums.size();
for(int i = 0 ; i < Size ; ++i)
{
/*2 conditions:*/
/*1.nums[i] ∈ [1,N]*/
/*2.avoid infinite loop*/
while(nums[i] > 0 && nums[i] <= Size && nums[i] != nums[nums[i] - 1])
swap(nums[i], nums[nums[i] - 1]);
}
for(int i = 0 ; i < Size ; ++i)
if(nums[i] != i + 1)
return i + 1;
return Size + 1;
}
边栏推荐
- Intel distiller Toolkit - Quantitative implementation 2
- R language ggplot2 visualization: place the title of the visualization image in the upper left corner of the image (customize Title position in top left of ggplot2 graph)
- [oc]- < getting started with UI> -- learning common controls
- CUDA realizes focal_ loss
- Leetcode: Sword Finger offer 42. Somme maximale des sous - tableaux consécutifs
- SAP ui5 date type sap ui. model. type. Analysis of the parsing format of date
- Implement window blocking on QWidget
- [today in history] February 13: the father of transistors was born The 20th anniversary of net; Agile software development manifesto was born
- Variable length parameter
- Improved deep embedded clustering with local structure preservation (Idec)
猜你喜欢
[today in history] February 13: the father of transistors was born The 20th anniversary of net; Agile software development manifesto was born
不同的数据驱动代码执行相同的测试场景
[oc]- < getting started with UI> -- common controls uibutton
Navicat Premium 创建MySql 创建存储过程
Promise 在uniapp的简单使用
[text generation] recommended in the collection of papers - Stanford researchers introduce time control methods to make long text generation more smooth
UnsupportedOperationException异常
Simple use of promise in uniapp
Intel distiller Toolkit - Quantitative implementation 3
CUDA实现focal_loss
随机推荐
[text generation] recommended in the collection of papers - Stanford researchers introduce time control methods to make long text generation more smooth
UML图记忆技巧
Intel distiller Toolkit - Quantitative implementation 3
LeetCode:26. Remove duplicates from an ordered array
使用标签模板解决用户恶意输入的问题
LeetCode:162. 寻找峰值
Cesium draw points, lines, and faces
CSP first week of question brushing
BN folding and its quantification
LeetCode:26. 删除有序数组中的重复项
Niuke winter vacation training 6 maze 2
不同的数据驱动代码执行相同的测试场景
数学建模2004B题(输电问题)
The ECU of 21 Audi q5l 45tfsi brushes is upgraded to master special adjustment, and the horsepower is safely and stably increased to 305 horsepower
[oc]- < getting started with UI> -- common controls - prompt dialog box and wait for the prompt (circle)
BMINF的后训练量化实现
How to effectively conduct automated testing?
LeetCode:836. 矩形重叠
Computer graduation design PHP Zhiduo online learning platform
[MySQL] limit implements paging