【LeetCode OJ 41】First Missing Positive

本文介绍了一种在未排序整型数组中找到第一个缺失正整数的方法。通过排序及筛选正数,再进行遍历比对,最终实现O(n)时间复杂度内解决问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值