题目链接:https://leetcode.com/problems/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.
解题思路:题意为给定一个未排序的整型数组,找出第一个遗漏的整数。可以通过Arrays的sort方法对其进行排序,然后将其中的正数放入另一个数组中,从头开始开始遍历,寻找第一个遗漏的整数。
示例代码:
public class Solution { public int firstMissingPositive(int[] nums) { if(nums.length<=0) return 1; Arrays.sort(nums); List<Integer> tempList=new ArrayList<Integer>(); for(int i=0;i<nums.length;i++) { if(!tempList.contains(nums[i])&&nums[i]>0) { tempList.add(nums[i]); } } if(tempList.size()==0) return 1; for(int i=0;i<tempList.size();i++) { if(tempList.get(i)!=(i+1)) { return i+1; } } return tempList.get(tempList.size()-1)+1; } }
【LeetCode OJ 41】First Missing Positive
原文:http://blog.csdn.net/xujian_2014/article/details/50564437