Leetcode 41: First Missing Positive

Posted Keep walking

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 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.

 

 1 public class Solution {
 2     public int FirstMissingPositive(int[] nums) {
 3         for (int i = 0; i < nums.Length; i++)
 4         {
 5             while (nums[i] > 0 && nums[i] <= nums.Length && nums[nums[i] - 1] != nums[i])
 6             {
 7                 var tmp = nums[nums[i] - 1];
 8                 nums[nums[i] - 1] = nums[i];
 9                 nums[i] = tmp;
10             }
11         }
12         
13         for (int i = 0; i < nums.Length; i++)
14         {
15             if (nums[i] != i + 1)
16             {
17                 return i + 1;
18             }
19         }
20         
21         return nums.Length + 1;
22     }
23 }

 



以上是关于Leetcode 41: First Missing Positive的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode 41. First Missing Positive

LeetCode OJ 41First Missing Positive

[array] leetcode - 41. First Missing Positive - Hard

[leetcode-41-First Missing Positive]

Leetcode 41: First Missing Positive

LeetCode41 First Missing Positive