first-missing-positive

来源:互联网 发布:古建筑三维模型软件 编辑:程序博客网 时间:2024/05/21 12:39

题目描述

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.

分析思路

如果用排序,时间复杂度也要nO(logn),如果用map,需要O(n)的空间。
采用如下思路;
将值放在它应该在的位置,最后再扫描一次得出哪个位置有缺少值。
如果该值小于0,忽略它;
如果该值大于0,A[i] = x,我们知道它应该被放在A[x-1]处,也就是交换A[i]与A[A[i]-1]

java实现

public int firstMissingPositive(int[] A) {        int i;        int n = A.length;        for(i=0; i<n;){            if(A[i]!= i+1 && A[i]>=1&&A[i]<=n && A[i] != A[A[i]-1]){                swap(A, i, A[i]-1);            }else                ++i;        }        for(i=0; i<n;i++){//扫描,            if(A[i] != i+1){                return i+1;            }        }        return n+1;    }    public void swap(int[] A, int i, int j){        if(i != j){            A[i] ^= A[j];            A[j] ^= A[i];            A[i] ^= A[j];        }    }}
原创粉丝点击