美文网首页
LeetCode每日一题:first missing posit

LeetCode每日一题:first missing posit

作者: yoshino | 来源:发表于2017-06-26 10:02 被阅读19次

问题描述

Given an unsorted integer array, find the first missing positive integer.
For example,
Given[1,2,0]return3,
and[3,4,-1,1]return2.
Your algorithm should run in O(n) time and uses constant space.

问题分析

这道题目有很多的方法来做,比如排序或者hashMap等,但是这题要求O(n)的时间复杂度和O(1)的空间复杂度,所以采用原数组置换的方式,把n放在数组A[n-1]的位置,那么从头开始遍历,当A[n-1]!=n时,n即为所求。

代码实现

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

相关文章

网友评论

      本文标题:LeetCode每日一题:first missing posit

      本文链接:https://www.haomeiwen.com/subject/yvpdcxtx.html