找出第一个缺失的正数

转载:https://blog.csdn.net/LaputaFallen/article/details/79966835

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

Example 1:

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

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

Input: [7,8,9,11,12]
Output: 1
1
2
Note: 
Your algorithm should run in O(n) time and uses constant extra space.

问题描述

给定一个未排序的整数数组,返回最小的缺失正整数

问题分析

若是排好序的正整数数组,为[1, 2, 3, 4, 5…],即i = n - 1(i为下标,n为元素值)

那么我们通过将”错位”的元素通过swap转换到它对应的位置,然后扫描数组就可以了

看一个例子,[1, 2, 0]

1已就位,2已就位,0跳过

从左到右扫描数组,发现只有下标为2处未就位,返回2 + 1,即3

解法

class Solution {
    public int firstMissingPositive(int[] nums) {
        int len = nums.length, i = 0;
        /*
        第一个if的三种情况分别为
        nums[i] <= 0, 非正数
        nums[i] == i + 1, 已就位
        nums[i] > len,元素值太大,无法找到合适的位置就位
        第二个表示元素值未就位,通过swap进行替换,归位
        第三个表示有重复元素,跳过即可
        */
        while(i < len){
            if(nums[i] <= 0 || nums[i] == i + 1 || nums[i] > len)   i++;
            else if(nums[nums[i] - 1] != nums[i])   swap(nums, i, nums[i] - 1);
            else    i++;
        }

        i = 0;
        while(i < len && nums[i] == i + 1)  i++;

        return i + 1;
    }
    public void swap(int[] nums, int a, int b){
        int temp =  nums[a];
        nums[a] = nums[b];
        nums[b] = temp;
    }
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值