当前位置:网站首页>41. 缺失的第一个正数
41. 缺失的第一个正数
2022-04-23 17:32:00 【hequnwang10】
一、题目描述
给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。
请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。
示例 1:
输入:nums = [1,2,0]
输出:3
示例 2:
输入:nums = [3,4,-1,1]
输出:2
示例 3:
输入:nums = [7,8,9,11,12]
输出:1
二、解题
数组视为哈希表(原地哈希)
将[1,n]中的元素放入i-1的下标 ,交换两个值,保证num[i]在i-1的下标,如果不存在,就放在那个位置 [1,n]之间。
class Solution {
public int firstMissingPositive(int[] nums) {
//将[1,n]中的元素放入i-1的下标 ,交换两个值
int length = nums.length;
for(int i = 0;i<length;i++){
//保证num[i]在i-1的下标,如果不存在,就放在那个位置 [1,n]之间
while(nums[i] > 0 && nums[i] <= length && nums[nums[i]-1] != nums[i]){
swap(nums,i,nums[i]-1);
}
}
//遍历数组
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://blog.csdn.net/hequnwang10/article/details/124210612
边栏推荐
- 2. Electron's HelloWorld
- Router object, route object, declarative navigation, programmed navigation
- 01 - get to know the advantages of sketch sketch
- Clickhouse SQL operation
- Conversion between hexadecimal numbers
- Use of todesk remote control software
- Generating access keys using JSON webtoken
- 1-3 components and modules
- 读《Software Engineering at Google》(15)
- Promise (III)
猜你喜欢
stm32入门开发板选野火还是正点原子呢?
. net type transfer
Net standard
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
440. 字典序的第K小数字(困难)-字典树-数节点-字节跳动高频题
In embedded system, must the program code in flash be moved to ram to run?
PC电脑使用无线网卡连接上手机热点,为什么不能上网
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
How to change input into text
Perception of linear algebra 2
随机推荐
How to change input into text
2. Electron's HelloWorld
Net standard
Conversion between hexadecimal numbers
Baidu Map Case - Zoom component, map scale component
[difference between Oracle and MySQL]
QT modification UI does not take effect
【生活中的逻辑谬误】稻草人谬误和无力反驳不算证明
Abnormal resolution of Xiaomi camera
Indexes and views in MySQL
MySQL installation
JS to find the character that appears three times in the string
. net cross platform principle (Part I)
. net type transfer
[simple understanding of database]
Tdan over half
Double pointer advanced -- leetcode title -- container with the most water
1-3 components and modules
.Net Core3. 1 use razorengine NETCORE production entity generator (MVC web version)
Ouvrir des contrats à terme, ouvrir des comptes en nuage ou faire confiance aux logiciels des sociétés à terme?