Skip to content

Commit bb16cde

Browse files
authored
Update readme.md
1 parent ff8e4ba commit bb16cde

File tree

1 file changed

+44
-1
lines changed
  • src/main/java/g0001_0100/s0041_first_missing_positive

1 file changed

+44
-1
lines changed

src/main/java/g0001_0100/s0041_first_missing_positive/readme.md

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,47 @@ You must implement an algorithm that runs in `O(n)` time and uses `O(1)` auxilia
3333
**Constraints:**
3434

3535
* <code>1 <= nums.length <= 10<sup>5</sup></code>
36-
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
36+
* <code>-2<sup>31</sup> <= nums[i] <= 2<sup>31</sup> - 1</code>
37+
38+
To solve the "First Missing Positive" problem in Java with a `Solution` class, we can follow these steps:
39+
40+
1. Define a `Solution` class.
41+
2. Define a method named `firstMissingPositive` that takes an array of integers `nums` as input and returns the smallest missing positive integer.
42+
3. Iterate through the array and mark the positive integers found by negating the value at the corresponding index.
43+
4. Iterate through the modified array again and return the index of the first positive number (which is the smallest missing positive integer).
44+
5. If no positive number is found, return `nums.length + 1`.
45+
46+
Here's the implementation:
47+
48+
```java
49+
public class Solution {
50+
public int firstMissingPositive(int[] nums) {
51+
int n = nums.length;
52+
53+
// Mark positive integers found by negating the value at the corresponding index
54+
for (int i = 0; i < n; i++) {
55+
if (nums[i] > 0 && nums[i] <= n) {
56+
int pos = nums[i] - 1;
57+
if (nums[pos] != nums[i]) {
58+
int temp = nums[pos];
59+
nums[pos] = nums[i];
60+
nums[i] = temp;
61+
i--; // Revisit the swapped number
62+
}
63+
}
64+
}
65+
66+
// Find the first positive number (smallest missing positive integer)
67+
for (int i = 0; i < n; i++) {
68+
if (nums[i] != i + 1) {
69+
return i + 1;
70+
}
71+
}
72+
73+
// If no positive number is found, return nums.length + 1
74+
return n + 1;
75+
}
76+
}
77+
```
78+
79+
This implementation provides a solution to the "First Missing Positive" problem in Java. It marks positive integers found by negating the value at the corresponding index and then iterates through the modified array to find the smallest missing positive integer. If no positive number is found, it returns `nums.length + 1`.

0 commit comments

Comments
 (0)