MrainW's Home

All things come to those who wait!

0%

LeetCode 41. First Missing Positive

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

  • Solution1
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++) {
//3142
//31-42
int num = Math.abs(nums[i]);
//3642
//最大是5,不需要操作,两个重要的点
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)

Welcome to my other publishing channels