Leetcode 41 First Missing Positive

本文介绍了一种在未排序整数数组中寻找最小缺失正整数的算法,该算法运行时间为O(n),并使用常数额外空间。通过示例说明了如何实现这一功能,并提供了完整的Java代码实现。

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

Given an unsorted integer array, find the smallest missing positive integer.

Example 1:

Input: [1,2,0]
Output: 3

Example 2:

Input: [3,4,-1,1]
Output: 2

Example 3:

Input: [7,8,9,11,12]
Output: 1

Note:

Your algorithm should run in O(n) time and uses constant extra space.

这个题是查找第一个最小的正整数。

public class Solution {
    public int firstMissingPositive(int[] nums) {
        if (nums == null || nums.length == 0)  // 防止越界
            return 1;
        for (int i = 0; i < nums.length; i++) {
            //    nums[i] - 1 < nums.length 超出范围不交换    nums[i] != nums[nums[i] - 1] 相等不交换
            while (nums[i] > 0 && nums[i] != i + 1 && nums[i] - 1 < nums.length && nums[i] != nums[nums[i] - 1]) {
                swap(nums, i, nums[i] - 1);
            }
        }
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != i + 1) {
                return i + 1;  // 第一个不相等就返回
            }
        }
        return nums[nums.length - 1] + 1;  // 数组交换后是有序正数,就返回最大 + 1
    }
 
    public void swap(int[] nums, int i, int j) {
        nums[i] = nums[i] ^ nums[j];
        nums[j] = nums[i] ^ nums[j];
        nums[i] = nums[i] ^ nums[j];
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值