-
Notifications
You must be signed in to change notification settings - Fork 2
/
FirstMissingPositive.java
65 lines (57 loc) · 1.5 KB
/
FirstMissingPositive.java
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package Leetcode;
/**
* @author kalpak
*
* Given an unsorted integer array nums, find the smallest missing positive integer.
*
* Follow up: Could you implement an algorithm that runs in O(n) time and uses constant extra space.?
*
*
*
* Example 1:
*
* Input: nums = [1,2,0]
* Output: 3
* Example 2:
*
* Input: nums = [3,4,-1,1]
* Output: 2
* Example 3:
*
* Input: nums = [7,8,9,11,12]
* Output: 1
*
*
* Constraints:
*
* 0 <= nums.length <= 300
* -231 <= nums[i] <= 231 - 1
*/
public class FirstMissingPositive {
public static int firstMissingPositive(int[] nums) {
for(int i = 0; i < nums.length; i++) {
while(nums[i] > 0 && nums[i] <= nums.length && nums[i] != nums[nums[i] - 1])
swap(nums, i, nums[i] - 1);
}
// for(int i = 0; i < nums.length; i++)
// System.out.print(nums[i] + " ");
for(int i = 0; i < nums.length; i++) {
if(nums[i] != i+1)
return i+1;
}
return nums.length+1;
}
private static void swap(int[] nums, int i, int j) {
nums[i] ^= nums[j];
nums[j] ^= nums[i];
nums[i] ^= nums[j];
}
public static void main(String[] args) {
int[] arr1 = new int[]{1, 2, 0};
int[] arr2 = new int[]{3, 4, -1, 1};
int[] arr3 = new int[]{7,8,9,10,11};
System.out.println(firstMissingPositive(arr1));
System.out.println(firstMissingPositive(arr2));
System.out.println(firstMissingPositive(arr3));
}
}