当前位置:网站首页>【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;
}
}
边栏推荐
猜你喜欢
二进制中负数为何要用补码形式来表示——二进制加减法
线程(上篇):线程的创建
【LeetCode】41、 缺失的第一个正数
【u-boot】u-boot驱动模型分析(02)
使用 DatePicker 日期控件,发生 Prop being mutated: “placement“ 报错问题
Rpc interface stress test
webrtc学习--websocket服务器(二) (web端播放h264)
告诉你如何从keil工程知道使用了多少RAM和ROM空间
文献 | 关于心理活动符号学,你知道多少?
栈与队列 | 有效的括号、删除字符串中的所有相邻元素、逆波兰表达式求值、滑动窗口的最大值、前K个高频元素 | leecode刷题笔记
随机推荐
解决“File has been changed outside the editor, reload?”提示
The sword refers to Offer 033. Variation array
重要转型升级
添加路由的2种方式--router
老博的往事
aliases节点分析
I have a dream for Career .
From entry to mastery of PHPCMS imitation station, Xiaobai is enough to watch this set of courses
软考考生注意!2022年下半年报名详细流程来了!
线程(下):读写者模型\环形队列\线程池
2022G3 Boiler Water Treatment Exam Mock 100 Questions and Mock Exam
oracle cdc时,设置并行度2插槽数1,最终任务只有一个tm,是不是因为oracle不支持并发
leetcode每天5题-Day11
flex related
SQLSERVER 2008 解析 Json 格式数据
SQL数据库字段追加到主表
最强大脑(1)
Kubernetes资源编排系列之一: Pod YAML篇
Rpc接口压测
EasyGBS connects to mysql database and prompts "can't connect to mysql server", how to solve it?