当前位置:网站首页>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
边栏推荐
- Qt 修改UI没有生效
- 给 el-dialog 增加拖拽功能
- Excel quickly and automatically fills the contents of a row on a blank cell
- . net cross platform principle (Part I)
- Use of todesk remote control software
- 古代埃及希腊,数学用的什么进制
- Qt error: /usr/bin/ld: cannot find -lGL: No such file or directory
- Use of shell sed command
- Shell - introduction, variables, and basic syntax
- Websocket (basic)
猜你喜欢

Halo 开源项目学习(二):实体类与数据表

Exercise: even sum, threshold segmentation and difference (two basic questions of list object)

Use of todesk remote control software

ASP. Net core dependency injection service life cycle

Bottom processing of stack memory in browser

JVM class loading mechanism

Use between nodejs modules
![Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers](/img/ec/43dddd18f0ce215f0f1a781e31f6a8.png)
Using quartz under. Net core -- job attributes and exceptions of [4] jobs and triggers

Deep understanding of control inversion and dependency injection

Matlab / Simulink simulation of double closed loop DC speed regulation system
随机推荐
Open futures, open an account, cloud security or trust the software of futures companies?
Exercise: even sum, threshold segmentation and difference (two basic questions of list object)
Entity Framework core captures database changes
Self use learning notes - connectingstring configuration
Shell-入门、变量、以及基本的语法
基于51单片机红外无线通讯仿真
Construction of functions in C language programming
HCIP第五次实验
Manually implement simple promise and its basic functions
uni-app黑马优购项目学习记录(下)
Advantages and disadvantages of several note taking software
Webapi + form form upload file
练习:求偶数和、阈值分割和求差( list 对象的两个基础小题)
開期貨,開戶雲安全還是相信期貨公司的軟件?
node中,如何手动实现触发垃圾回收机制
2. Electron's HelloWorld
Allowed latency and side output
Scope and scope chain in JS
Tdan over half
Abnormal resolution of Xiaomi camera