当前位置:网站首页>【LeetCode】41. The first missing positive number
【LeetCode】41. The first missing positive number
2022-08-10 05:04:00 【Xiaoqu classmate】
41、 缺失的第一个正数
题目:
给你一个未排序的整数数组 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 <= nums.length <= 5 * 105
-231 <= nums[i] <= 231 - 1
解题思路:
(原地哈希) O(n)
对于一个长度为 n 的数组,其中没有出现的最小正整数只能在[1, n + 1]中.这是因为如果[1, n] 都出现了,那么答案是 n + 1,否则答案是[1, n]中没有出现的最小正整数.
时间复杂度分析:
Although it seems to be a two-layer loop,But the innermostwhile循环,每循环一次,A number will be placed in the correct position,所以总共最多执行 n 次,因此总的时间复杂度为 O(n)
空间复杂度分析:No extra arrays are used,因此空间复杂度为O(1).
参考代码:
class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
for(int i = 0; i < n; i++){
while(nums[i] >= 1 && nums[i] <= n && nums[i] != nums[nums[i] - 1]) {
int temp = nums[nums[i] - 1];
nums[nums[i] - 1] = nums[i];
nums[i] = temp;
}
}
for(int i = 0; i < n ; i++)
if( nums[i] != i + 1)
return i + 1;
return n + 1;
}
}

边栏推荐
猜你喜欢
随机推荐
oracle cdc时,设置并行度2插槽数1,最终任务只有一个tm,是不是因为oracle不支持并发
Pulsar中游标的工作原理
安芯电子IPO过会:年营收4亿 汪良恩兄弟持股61.6%
redis基本数据类型
openvino 安装(01)
取消了这次
电流探头如何设置示波器参数
干货 | 查资料利器:线上图书馆
顺序表的删除,插入和查找操作
老博的往事
FPGA工程师面试试题集锦21~30
An article to master the entire JVM, JVM ultra-detailed analysis!!!
redis basic data types
2022 R2 transportable pressure vessel filling operation examination question bank simulation platform
EasyGBS connects to mysql database and prompts "can't connect to mysql server", how to solve it?
一篇文章掌握整个JVM,JVM超详细解析!!!
如何取得某月的最后一天
webrtc学习--websocket服务器
`id` bigint(20) unsigned NOT NULL COMMENT 'Database primary key',
Unity实现UI的边缘检测和拖拽拉伸功能









