File tree Expand file tree Collapse file tree 1 file changed +21
-8
lines changed
solution/0000-0099/0041.First Missing Positive Expand file tree Collapse file tree 1 file changed +21
-8
lines changed Original file line number Diff line number Diff line change 1
- class Solution {
2
- public int firstMissingPositive (int [] nums ) {
3
- int re = 1 ;
4
- Arrays . sort ( nums );
5
- for ( int num : nums ) {
6
- if ( num == re ) re ++ ;
7
- if ( num > re ) return re ;
1
+ public class Solution {
2
+ public int firstMissingPositive (int [] num ) {
3
+ for ( int i = 0 ; i < num . length ; i ++) {
4
+ if ( num [ i ] > 0 && num [ i ] < num . length && num [ num [ i ] - 1 ] != num [ i ]) {
5
+ swap ( num , i , num [ i ] - 1 );
6
+ i -- ;
7
+ }
8
8
}
9
- return re ;
9
+
10
+ for (int i = 0 ; i < num .length ; i ++) {
11
+ if (i + 1 != num [i ]) {
12
+ return i + 1 ;
13
+ }
14
+ }
15
+
16
+ return num .length + 1 ;
17
+ }
18
+
19
+ private void swap (int [] num , int i , int j ) {
20
+ int temp = num [i ];
21
+ num [i ] = num [j ];
22
+ num [j ] = temp ;
10
23
}
11
24
}
You can’t perform that action at this time.
0 commit comments