首页 > 其他 > 详细

【LeetCode OJ 41】First Missing Positive

时间:2016-01-25 17:21:37      阅读:196      评论:0      收藏:0      [点我收藏+]

题目链接: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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!