【LeetCode OJ 41】First Missing Positive

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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值