41. First Missing Positive

本文介绍了一种寻找数组中最小缺失正整数的方法。通过手动排序将数值置于正确的位置,并检查是否有重复值,最终遍历数组找出第一个不匹配其索引的值,即为所求。此算法时间复杂度为O(n),空间复杂度为O(1)。

一刷。

这个题还是挺难的= =有一点需要利用的就是数组长度和数组里面数的值域关系。

数组长度是n,那么数字只可以是1-n。
做法是手动排序,把数字放到相应位置。
超出数组范围的>n or 0,不动。
可以放到相应位置的,放之前看看是不是有重复的,有点话不动= =;没有就和那个位置的元素互换位置。

最后遍历数组,和下标不符合规矩的就是缺失的。

都不缺失说明缺少n+1...

Time: O(n)
Space: O(1)

public class Solution {
    public int firstMissingPositive(int[] nums) {
        if (nums.length == 0) return 1;
        
        int i = 0;
        while (i < nums.length) {
            
            if (nums[i] <= 0 || nums[i] > nums.length) { // invalid cuz out of range
                i ++;
            } else if (nums[i] != nums[nums[i] - 1]) {  // swap to where it should be..if no duplicates
                swap(nums, i, nums[i] - 1);
            } else {                                    // duplicates= =
                i ++;
            }
            
        }
        
        for (int j = 0; j < nums.length; j++) {
            if (nums[j] != j + 1) {
                return j + 1;
            }
        }
        return nums.length + 1;
    }
    
    public void swap(int[] nums, int a, int b) {
        int temp = nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}

转载于:https://www.cnblogs.com/reboot329/p/6168409.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值