当前位置:网站首页>41. The first missing positive number
41. The first missing positive number
2022-04-23 17:32:00 【hequnwang10】
One 、 Title Description
Here's an unsorted array of integers nums , Please find the smallest positive integer that doesn't appear in it .
Please implement a time complexity of O(n) And solutions that use only constant level extra space .
Example 1:
Input :nums = [1,2,0]
Output :3
Example 2:
Input :nums = [3,4,-1,1]
Output :2
Example 3:
Input :nums = [7,8,9,11,12]
Output :1
Two 、 Problem solving
The array is treated as a hash table ( In situ hash )
take [1,n] Put the elements in i-1 The subscript , Exchange two values , Guarantee num[i] stay i-1 The subscript , If it doesn't exist , Just put it in that position [1,n] Between .
class Solution {
public int firstMissingPositive(int[] nums) {
// take [1,n] Put the elements in i-1 The subscript , Exchange two values
int length = nums.length;
for(int i = 0;i<length;i++){
// Guarantee num[i] stay i-1 The subscript , If it doesn't exist , Just put it in that position [1,n] Between
while(nums[i] > 0 && nums[i] <= length && nums[nums[i]-1] != nums[i]){
swap(nums,i,nums[i]-1);
}
}
// Traversal array
for(int i = 0;i<length;i++){
if(nums[i] != i+1){
return i+1;
}
}
return length+1;
}
public void swap(int[] nums,int left,int right){
int temp = nums[left];
nums[left] = nums[right];
nums[right] = temp;
}
}
版权声明
本文为[hequnwang10]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231732009892.html
边栏推荐
- Perception of linear algebra 2
- Further study of data visualization
- tidb-server 的配置文件在哪里?
- Clickhouse - data type
- Understanding and small examples of unity3d object pool
- Metaprogramming, proxy and reflection
- Shell - introduction, variables, and basic syntax
- Further optimize Baidu map data visualization
- uni-app黑马优购项目学习记录(下)
- node中,如何手动实现触发垃圾回收机制
猜你喜欢
随机推荐
PC uses wireless network card to connect to mobile phone hotspot. Why can't you surf the Internet
Ouvrir des contrats à terme, ouvrir des comptes en nuage ou faire confiance aux logiciels des sociétés à terme?
Excel quickly and automatically fills the contents of a row on a blank cell
Use of shell cut command
Websocket (basic)
JVM class loading mechanism
Bottom processing of stack memory in browser
Further study of data visualization
XTask与Kotlin Coroutine的使用对比
Entity Framework core captures database changes
For the space occupation of the software, please refer to the installation directory
C listens for WMI events
Node template engine (EJS, art template)
EF core in ASP Generate core priority database based on net entity model
STM32 entry development board choose wildfire or punctual atom?
C dapper basically uses addition, deletion, modification and query transactions, etc
Come out after a thousand calls
Some problems encountered in recent programming 2021 / 9 / 8
How to change input into text
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk







![Using quartz under. Net core - [1] quick start](/img/80/b99417e88d544ca6e3da4c0c1625ce.png)
