41. 缺失的第一个正数

给你一个未排序的整数数组 nums ,请你找出其中没有出现的最小的正整数。

请你实现时间复杂度为 O(n) 并且只使用常数级别额外空间的解决方案。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/first-missing-positive
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

class Solution {

    private void swap(int[] nums, int a, int b) {
        int tmp = nums[a];
        nums[a] = nums[b];
        nums[b] = tmp;
    }

    public int firstMissingPositive(int[] nums) {
        int index = 0, right = nums.length - 1;

        while (index <= right) {
            if (nums[index] == index + 1) {
                index++;
            } else if (nums[index] < index + 1 || nums[index] > right + 1) {
                swap(nums, index, right--);
            } else {
                if (nums[nums[index] - 1] == nums[index]) {
                    swap(nums, index, right--);
                } else {
                    swap(nums, index, nums[index] - 1);
                }
            }
        }


        return index + 1;
    }
}
posted @ 2021-12-13 23:31  Tianyiya  阅读(53)  评论(0)    收藏  举报