First Missing Positive (Java)

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

For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.

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

这道题的最小数据是从<=0开始的,找乱序数组中第一个缺失的正整数。这样的题设条件,使得可以使用hashset来做,只需要i从1开始遍历,找第一个在hashset中不存在的数即可。空间复杂度会很高。

另一种方法是用A[]本身做hash,将i放置在i - 1的位置上。遍历数组,如果i不在i - 1上就将其与放在i - 1位置上的数交换。

Source1

    public int firstMissingPositive(int[] A) {
    	HashSet<Integer> hs = new HashSet<Integer>();
    	
    	for(int i = 0; i < A.length; i++){
    		if(A[i] > 0) hs.add(A[i]);
    	}
    	
    	for(int i = 1; ; i++){
    		if(!hs.contains(i)) return i;
    	}
    }


Test

    public static void main(String[] args){
    	int[] A = {1,2,5,6,4};
    	System.out.println(new Solution().firstMissingPositive(A));
      
    }


Source2

    public int firstMissingPositive(int[] A) {
    	for(int i = 0; i < A.length; i++){
    		if(A[i] > 0 && A[i] <= A.length && A[i] != A[A[i] - 1]){
    			//由于最小数是<=0的,所以数组中>A.length的数不用考虑,也没地方放
    			//数字i应当等于放在i-1的位置上的值,比如数字3,应当放在2的位置上
    			int temp = A[A[i] - 1];
    			A[A[i] - 1] = A[i];
    			A[i] = temp;
    			i --; //交换完该位置上的数不一定是该位置上应有的数,所以重新判断
    		}
    		
    	}
    	
    	for(int i = 0; i < A.length; i++){
    		if(A[i] != i + 1)
    			return i + 1;
    	}
    	return A.length + 1;
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值