码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode 41: First Missing Positive

时间:2018-01-22 11:09:28      阅读:162      评论:0      收藏:0      [点我收藏+]

标签:class   mis   space   pac   integer   col   algorithm   ons   post   

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

标签:class   mis   space   pac   integer   col   algorithm   ons   post   

原文地址:https://www.cnblogs.com/liangmou/p/8327656.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!