-
Notifications
You must be signed in to change notification settings - Fork 180
Expand file tree
/
Copy pathq041_FirstMissingPositive.java
More file actions
49 lines (37 loc) · 1.23 KB
/
q041_FirstMissingPositive.java
File metadata and controls
49 lines (37 loc) · 1.23 KB
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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package leetcode_algorithm;
/**
Given an unsorted integer array, find the first missing positive integer.
For example,
Given [1,2,0] return 3,
and [3,4,-1,1] return 2.
Your algorithm should run in O(n) time and uses constant space.
*/
public class q041_FirstMissingPositive {
public static void main(String[] args) {
System.out.println(new q041_FirstMissingPositive().firstMissingPositive(new int[]{1, 2, 0}));
System.out.println(new q041_FirstMissingPositive().firstMissingPositive(new int[]{3, 4, -1, 1}));
System.out.println(new q041_FirstMissingPositive().firstMissingPositive(new int[]{7, 8, 1, 2}));
}
/**
* ½â·¨1
*
* @param nums
* @return
*/
public int firstMissingPositive(int[] nums) {
int i = 0;
while (i < nums.length) {
if(nums[i] == i+1 || nums[i] <= 0 || nums[i] > nums.length) i++;
else if(nums[nums[i] - 1] != nums[i]) swap(nums , i , nums[i] - 1);
else i++;
}
i = 0;
while(i < nums.length && nums[i] == i+1) i++;
return i+1;
}
private void swap(int[] A, int i, int j) {
int temp = A[i];
A[i] = A[j];
A[j] = temp;
}
}