A simple solution in Java


  • 0
    H
    public int firstMissingPositive(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 1;
        }
        for (int i = 0; i < nums.length; i++) {
            while (nums[i] > 0 && nums[i] <= nums.length && nums[i] != i + 1) {
                int temp = nums[nums[i] - 1];
                if (temp == nums[i]) {
                    break;
                } else {
                    nums[nums[i] - 1] = nums[i];
                    nums[i] = temp;
                }
            }
        }
        int i = 0;
        while (i < nums.length) {
            if (nums[i] != i + 1) {
                return i + 1;
            }
            i++;
        }
        return i + 1;
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.