资讯专栏INFORMATION COLUMN

[LeetCode] 41. First Missing Positive

30e8336b8229 / 2000人阅读

Problem

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

Example 1:

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

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

Input: [7,8,9,11,12]
Output: 1
Note:

Your algorithm should run in O(n) time and uses constant extra space.

Solution
class Solution {
    public int firstMissingPositive(int[] A) {
        int i = 0;
        while(i < A.length){
            //we want every A[i] = i+1, so we can find the first missing one
            //if A[i] is negative or out of scope, or it"s in desired position, continue
            if(A[i] == i+1 || A[i] <= 0 || A[i] > A.length) i++;
            //if the number at the desired position of A[i] isn"t A[i], swap them
            else if(A[A[i]-1] != A[i]) swap(A, i, A[i]-1);
            //otherwise, A[A[i]-1] == A[i], we have a duplicate, move on
            else i++;
        }
        
        //now check from the beginning
        i = 0;
        while(i < A.length && A[i] == i+1) i++;
        return i+1;
    }
    
    private void swap(int[] A, int i, int j){
        int temp = A[i];
        A[i] = A[j];
        A[j] = temp;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72601.html

相关文章

  • leetcode 41. First Missing Positive

    摘要:题目要求在数组中找到第一个漏掉的正整数。思路一暴力排序后寻找排序后寻找显然是最快的。这些临时变量可以是排除出的量,也可以是有效量。当遇到的数字为有效数字时,则将该数字放到对应当前起始下标其相应的位置上。 题目要求 Given an unsorted integer array, find the first missing positive integer. For example,...

    smallStone 评论0 收藏0
  • LeetCode 之 JavaScript 解答第41题 —— 缺失的第一个正数(First Mis

    摘要:小鹿题目算法思路桶排序思想。再遍历数组,从下标开始判断该下标是否存放规定的数据,如果不是则该下标就是这组数据中缺失的最小正整数。桶排序还可以实现在一组数据中查找重复的数据。 Time:2019/4/6Title: First Missing PositiveDifficulty: DifficultyAuthor: 小鹿 题目:First Missing Positive Give...

    levius 评论0 收藏0
  • [LintCode] First Missing Positive

    摘要:找第一个缺失的正整数,只要先按顺序排列好,也就是,找到第一个和不对应的数就可以了。注意数组的从开始,而正整数从开始,所以重写排列的时候要注意换成,而就是从开始的数组中的元素。 Problem Given an unsorted integer array, find the first missing positive integer. Example Given [1,2,0] re...

    snifes 评论0 收藏0
  • [Leetcode] Missing Number and Missing First Positi

    摘要:代码映射法复杂度时间空间思路核心思想就是遍历数组时,将每个元素,和以该元素为下标的元素进行置换,比如第一个元素是,就将它置换到下标为的地方,而原本下标为的地方的元素就换到第一个来。 Missing Number Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one t...

    Forest10 评论0 收藏0
  • leetcode376. Wiggle Subsequence

    摘要:题目要求扭动序列是指数组中的相邻两个元素的差保证严格的正负交替,如数组中相邻两个元素的差为,满足扭动序列的要求。现在要求从一个数组中,找到长度最长的扭动子序列,并返回其长度。即前一个元素和当前元素构成下降序列,因此代码如下 题目要求 A sequence of numbers is called a wiggle sequence if the differences between ...

    CoffeX 评论0 收藏0

发表评论

0条评论

30e8336b8229

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<