前 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;
    }
}
posted @ 2018-09-05 14:48  Echie  阅读(118)  评论(0编辑  收藏  举报