41. First Missing Positive

网友投稿 705 2022-09-04

41. First Missing Positive

41. First Missing Positive

Given an unsorted integer array, find the first missing positive integer.

For example, Given [1,2,0] return 3, and [3,4,-1,1] return 2.

Your algorithm should run in O(n) time and uses constant space.

class Solution { public int firstMissingPositive(int[] nums) { if(nums.length == 0) return 1; //第i位存放i+1的数值 for(int i = 0; i < nums.length;i++){ if(nums[i] > 0){//nums[i]为正数,放在i+1位置 //假设交换的数据还是大于0且 0 && nums[i] < i+1 && 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 < nums.length;i++){ if(nums[i] != i+1){ return i+1; } } //假设都符合要求,则返回长度+1的值 return nums.length + 1; }}

class Solution { public int firstMissingPositive(int[] nums) { int[] tempNums = new int[nums.length]; for (int i = 0; i 0 ){ tempNums[nums[i]-1] = nums[i] ; } } for (int k = 0; k

class Solution: def firstMissingPositive(self, nums: List[int]) -> int: counter = 1 #smallest possible while True: if counter not in nums: return counter else: counter += 1

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:非阻塞模式与PHP多进程(php阻塞和非阻塞)
下一篇:400. Nth Digit
相关文章

 发表评论

暂时没有评论,来抢沙发吧~