You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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
+
publicclassSolution {
50
+
publicintfirstMissingPositive(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