zoukankan      html  css  js  c++  java
  • 前 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;
        }
    }
    
  • 相关阅读:
    day10 测试2
    算法题
    day10 自动化测试
    day09 测试
    进行试验,对比
    多层网络的SIR实现
    day08 商城项目
    day07 cookie session 模板
    day06 模型类
    纸上谈兵:图(graph)
  • 原文地址:https://www.cnblogs.com/echie/p/9592060.html
Copyright © 2011-2022 走看看