码迷,mamicode.com
首页 > 编程语言 > 详细

前 n 个数原址排序的问题

时间:2018-09-05 17:32:51      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:public   案例   int   and   output   integer   访问   gpo   []   

[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;
    }
}

前 n 个数原址排序的问题

标签:public   案例   int   and   output   integer   访问   gpo   []   

原文地址:https://www.cnblogs.com/echie/p/9592060.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!