当前位置:网站首页>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
边栏推荐
- ClickHouse-表引擎
- [C] thoroughly understand the deep copy
- Simulation of infrared wireless communication based on 51 single chip microcomputer
- Node template engine (EJS, art template)
- Devexpress GridView add select all columns
- Seven cattle upload pictures (foreground JS + background C API get token)
- [batch change MySQL table and corresponding codes of fields in the table]
- Construction of functions in C language programming
- . net cross platform principle (Part I)
- 2.Electron之HelloWorld
猜你喜欢
1-4 configuration executable script of nodejs installation
Double pointer advanced -- leetcode title -- container with the most water
2. Electron's HelloWorld
【WPF绑定3】 ListView基础绑定和数据模板绑定
快时钟同步慢时钟域下的异步控制信号slow clk to fast clk
Why do some people say SCM is simple and I have to learn it so hard?
EF core in ASP Generate core priority database based on net entity model
JVM类加载机制
Collection of common SQL statements
01 - get to know the advantages of sketch sketch
随机推荐
Shell-sed命令的使用
Indexes and views in MySQL
Using quartz under. Net core - calendar of [6] jobs and triggers
ASP. Net core dependency injection service life cycle
Excel quickly and automatically fills the contents of a row on a blank cell
stm32入门开发板选野火还是正点原子呢?
Promise (II)
Further study of data visualization
198. 打家劫舍-动态规划
Understanding and small examples of unity3d object pool
Net standard
基于51单片机红外无线通讯仿真
ClickHouse-数据类型
Using quartz under. Net core -- a simple trigger of [7] operation and trigger
线性代数感悟之2
Why do some people say SCM is simple and I have to learn it so hard?
JS to find the character that appears three times in the string
Header built-in object
读《Software Engineering at Google》(15)
Seven cattle upload pictures (foreground JS + background C API get token)