【Leetcode】41. 缺失的第一个正整数(First Missing Positive)

Leetcode - 41 First Missing Positive (Hard)

Input: [3,4,-1,1]
Output: 2
public int firstMissingPositive(int[] nums) {
    int i = 0; 
    while (i < nums.length) {
        if (nums[i] >= 1 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1]) {
            swap(nums, i, nums[i] - 1);
        } else {
            i++;
        }
    }
    i = 0;
    while (i < nums.length && nums[i] == i + 1) i++;
    return i + 1;
}

public void swap (int[] A, int a, int b) {
    int tmp = A[a];
    A[a] = A[b];
    A[b] = tmp;
}

你可能感兴趣的:(LeetCode,精选Top面试题,数组)