LeetCode(7)

来源:互联网 发布:php采集网页内容 编辑:程序博客网 时间:2024/06/05 11:10

https://leetcode.com/problems/first-missing-positive/#/description


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.


Solution:

本题的的目的是在于寻找第一个缺失的整数,方法有两种。

一种是新开一个数组,由于要使用常数空间,所以这种不行。

一种是对数组进行简单排序,我们的思路是将非负数放到其对应的Index上,例如1就放到0,2就放到1,以此类推。

最后遍历数组,寻找index不符合的数值输出。

这里有两点需要注意的:

1、交换位置时,需要持续交换,直到满足出现非负数或者符合当前index的数

2、注意[1, 1]这样的情况,容易导致1卡死。


public int firstMissingPositive(int[] nums) {    for(int i = 0; i < nums.length; i++) {        while(nums[i] > 0 && nums[i] <= nums.length && nums[i] != i + 1) {            if (nums[i] == nums[nums[i] - 1]) {                break;            }            int temp = nums[nums[i] - 1];            nums[nums[i] - 1] = nums[i];            nums[i] = temp;        }    }    for(int i = 0; i < nums.length; i++) {        if (nums[i] != i + 1) {            return i + 1;        }    }    return nums.length + 1;}

0 0
原创粉丝点击