leetcode数组专项习题:第一个丢失的正数

版权声明:本文为博主原创,未经允许请不要转载哦 https://blog.csdn.net/weixin_43277507/article/details/88178317

15、第一个丢失的正数
first-missing-positive: 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.
题目要求:给定未排序的整数数组,找到第一个缺少的正整数。
例如,Given [1,2,0] return 3,[3,4,-1,1] return 2。
您的算法应该在O(n)时间运行并使用恒定空间。
分析:题设对于时间复杂度和空间复杂度都提出了要求。使用常数空间,我们可以考虑运用数组本身来充当哈希表。在遍历数组的时候,把数字i放在A[i-1]的位置。如果A【k】!=k+1,那么这个正数就没有出现过。
此外,需要注意的是,我们需要用if判断条件A[i]!=A[A[i]-1].如果某个位置A[i]已经放置了i+1或者数字A[i]即将要放入的位置A[A[i]-1]原本就是A[i]则跳过,避免出现死循环。
代码如下:

public class Solution{
    public static void main(String[] args) 
    {
    	Solution sl = new Solution();
        int[] A= {3,4,-1,1};
        int number=sl.firstMissingPositive(A);
        System.out.println(number);
     }
    
    public int firstMissingPositive(int[] A) 
    {
    	int n=A.length;
        for(int i=0;i<n;)
        {
            if(A[i]>0&&A[i]<=n&&A[i]!=A[A[i]-1])
            {
            	int index=A[i];
            	int temp = index;
            	A[i]=A[index-1];
            	A[index-1]=temp;
            }
            else
            {
            	++i;
            }
        }
        for(int i=0;i<n;i++)
        {
        	if(A[i]!=i+1) return i+1;
        }
        return n+1;
    }

}

猜你喜欢

转载自blog.csdn.net/weixin_43277507/article/details/88178317