Question
Given an unsorted integer array nums
, return the smallest missing positive integer.
You must implement an algorithm that runs in O(n)
time and uses constant extra space.
https://leetcode.com/problems/first-missing-positiv
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| class Solution { public int firstMissingPositive(int[] nums) { if (nums == null || nums.length == 0) return 1; for (int i = 0; i < nums.length; i++) { if (nums[i] <= 0){ nums[i] = Integer.MAX_VALUE; } } for (int i = 0; i < nums.length; i++) { int num = Math.abs(nums[i]); if (num <= nums.length) { nums[num - 1] = -Math.abs(nums[num - 1]); } } for (int i = 0; i < nums.length; i++) { if (nums[i] > 0) { return i + 1; } } return nums.length + 1; } }
|
Complexity:
Time complexity: O(n)
Space complexity: O(1)