File tree 3 files changed +85
-0
lines changed
Find All Duplicates in an Array
Find All Numbers Disappeared in an Array
3 files changed +85
-0
lines changed Original file line number Diff line number Diff line change
1
+ // Runtime: 116 ms, faster than 68.53% of C++ online submissions for Find All Duplicates in an Array.
2
+ // Memory Usage: 14.8 MB, less than 100.00% of C++ online submissions for Find All Duplicates in an Array.
3
+
4
+ class Solution
5
+ {
6
+ public:
7
+ vector<int > findDuplicates (vector<int >& nums)
8
+ {
9
+ for (int index = 0 ; index < nums.size (); ++index )
10
+ {
11
+ while (nums[index ] != index + 1 )
12
+ {
13
+ if (nums[index ] == nums[nums[index ] - 1 ]) break ;
14
+ swap (nums[index ], nums[nums[index ] - 1 ]);
15
+ }
16
+ }
17
+
18
+ vector<int > res;
19
+ for (int index = 0 ; index < nums.size (); ++index )
20
+ {
21
+ if (nums[index ] != index + 1 )
22
+ {
23
+ res.push_back (nums[index ]);
24
+ }
25
+ }
26
+
27
+ return res;
28
+ }
29
+ };
Original file line number Diff line number Diff line change
1
+ // Runtime: 116 ms, faster than 68.68% of C++ online submissions for Find All Numbers Disappeared in an Array.
2
+ // Memory Usage: 14.9 MB, less than 86.67% of C++ online submissions for Find All Numbers Disappeared in an Array.
3
+
4
+ class Solution
5
+ {
6
+ public:
7
+ vector<int > findDisappearedNumbers (vector<int >& nums)
8
+ {
9
+ for (int index = 0 ; index < nums.size (); ++index )
10
+ {
11
+ while (nums[index ] != index + 1 )
12
+ {
13
+ if (nums[index ] == nums[nums[index ] - 1 ]) break ;
14
+ swap (nums[index ], nums[nums[index ] - 1 ]);
15
+ }
16
+ }
17
+
18
+ vector<int > res;
19
+ for (int index = 0 ; index < nums.size (); ++index )
20
+ {
21
+ if (nums[index ] != index + 1 )
22
+ {
23
+ res.push_back (index + 1 );
24
+ }
25
+ }
26
+
27
+ return res;
28
+ }
29
+ };
Original file line number Diff line number Diff line change
1
+ // Runtime: 24 ms, faster than 11.13% of C++ online submissions for Move Zeroes.
2
+ // Memory Usage: 9.5 MB, less than 75.00% of C++ online submissions for Move Zeroes.
3
+
4
+ class Solution
5
+ {
6
+ public:
7
+ void moveZeroes (vector<int >& nums)
8
+ {
9
+ if (nums.empty ()) return ;
10
+
11
+ int slowPtr = 0 , fastPtr = 0 ;
12
+
13
+ while (fastPtr < nums.size ())
14
+ {
15
+ while (fastPtr < nums.size () && nums[fastPtr] == 0 ) ++fastPtr;
16
+
17
+ if (fastPtr >= nums.size ()) break ;
18
+
19
+ nums[slowPtr++] = nums[fastPtr++];
20
+ }
21
+
22
+ while (slowPtr < nums.size ())
23
+ {
24
+ nums[slowPtr++] = 0 ;
25
+ }
26
+ }
27
+ };
You can’t perform that action at this time.
0 commit comments