Leetcode41. 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.

思路

利用hash的思想來做
PS:在本地測試的時候,將中間結果打印出來

測試用例

[]
[0]
[1]
[-1]
[-1, 2, 3, 5, 1 , 6]

代碼

public class Solution {
    public int firstMissingPositive(int[] nums) {


        for(int i = 0; i < nums.length; i++){
            while(nums[i] > 0 && nums[i] < nums.length && nums[ nums[i] - 1] != nums[i])
                swap(nums, i, nums[i] - 1);
        }

        for(int i = 0 ; i < nums.length; i++){
            if(nums[i] != i + 1)
                return i + 1;
        }
        return nums.length + 1;

    }
    void swap(int[] nums, int left, int right){
        int temp = nums[left];
        nums[left] = nums[right];
        nums[right] = temp;
    }
}

結果

這裏寫圖片描述

他山之玉

class Solution
{
public:
    int firstMissingPositive(int A[], int n)
    {
        for(int i = 0; i < n; ++ i)
            while(A[i] > 0 && A[i] <= n && A[A[i] - 1] != A[i])
                swap(A[i], A[A[i] - 1]);

        for(int i = 0; i < n; ++ i)
            if(A[i] != i + 1)
                return i + 1;

        return n + 1;
    }
};
public class Solution {
    public int firstMissingPositive(int[] nums) {
        // nums[i] -> i+1
        int next;
        for (int i = 0 ; i < nums.length; i++) {
            int curr = nums[i];
            if (curr > 0 && curr != i+1 && curr <= nums.length) {
                do {
                    next = nums[curr-1];
                    nums[curr-1] = curr;
                    curr = next;
                } while (curr > 0 && curr <= nums.length && nums[curr-1] != curr);
            }
        }
        int j;
        for (j = 0; j < nums.length; j++) {
            if (nums[j] != j+1)
                break;
        }
        return j+1;
    }
}
def firstMissingPositive(self, A):
    num = 0
    for i in A:
        if i > 0:
            num = num | (1 << i)
    x = 1
    while True:
        if (1 << x) & num == 0:
            return x
        x += 1
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章