Friday, April 15, 2016

[LeetCode] 41. First Missing Positive

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.
1. Swapping, kept swapping out of range elements beyond the end of array index.
public class Solution {
    
    private void swap(int[] nums, int i, int j){
        nums[i] = nums[i] ^ nums[j];
        nums[j] = nums[j] ^ nums[i];
        nums[i] = nums[i] ^ nums[j];
    }
    
    public int firstMissingPositive(int[] nums) {
        int len = nums.length;
        
        if(0 == len)
            return 1;
        
        int tail = len-1;   
           
        for(int i = 0; i < len; ++i){
            while(nums[i] != i+1 && tail >= i){
                if(nums[i] > tail+1 || nums[i] <= i){
                    // discard it
                    nums[i] = nums[tail--];
                }else{
                    if(nums[nums[i]-1] == nums[i]){
                        nums[i] = nums[tail--];
                    }
                    else{
                        swap(nums, i, nums[i]-1);
                    }
                }    
            }
            
            if(tail < i)
                return tail+2;
        }
        
        return len+1;
    }
}

No comments:

Post a Comment