前 n 个数原址排序的问题

本文介绍了解决LeetCode第41题的方法,该题要求在未排序的整数数组中找到最小的缺失正整数。算法需在O(n)时间内运行并使用常数级额外空间。通过遍历数组元素并进行适当交换来实现这一目标。

[LeetCode 41] First Missing Positive

题目

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

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

测试案例

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

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

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

思路

从左往右遍历每一个元素

  • 如果 nums[i] = i + 1 或者 nums[i] 的值在 1 ~ n 范围之外,遍历下一个元素。
  • 否则,应该将 nums[i] 放到下标 nums[i] - 1 处,如果此下标中已经存放了 nums[i] - 1。则说明数组中存在重复元素。i 处的元素多余。那么,继续遍历下一个元素。
  • 否则,交换 i 和 nums[i] - 1 处的元素。然后重新访问 i 处的元素。

代码如下

class Solution {
    public int firstMissingPositive(int[] nums) {
        int n = nums.length, index, i = 0;
        while(i < n){
            if((index = nums[i]) <= 0 || nums[i] > n || nums[index - 1] == index){
                i++;
            }
            else{
                nums[i] = nums[index - 1];
                nums[index - 1] = index;
            }
        }
        for(i = 0; i < n && nums[i] == i + 1; i++);
        return i + 1;
    }
}

转载于:https://www.cnblogs.com/echie/p/9592060.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值