Skip to content

Commit 5c886ba

Browse files
committed
Sync LeetCode submission - Remove Element (c)
1 parent 281349f commit 5c886ba

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
void swapElements(int*, int, int);
2+
int removeElement(int* nums, int numsSize, int val) {
3+
if (numsSize == 0) { return 0; };
4+
if (numsSize == 1) {
5+
return *nums != val;
6+
}
7+
8+
int current_idx = 0;
9+
int final_safe_pos = numsSize - 1;
10+
11+
// Get final_safe_pos to a point where it is safe
12+
while (*(nums + final_safe_pos) == val) {
13+
--final_safe_pos;
14+
if (current_idx == final_safe_pos) {
15+
if (*nums == val) {
16+
return 0;
17+
} else {
18+
return 1;
19+
}
20+
}
21+
}
22+
23+
// Start moving the index upwards
24+
while ((current_idx + 1) <= final_safe_pos) {
25+
if (*(nums + current_idx) == val) {
26+
swapElements(nums, current_idx, final_safe_pos);
27+
while (*(nums + final_safe_pos) == val) {
28+
if (final_safe_pos == 0) {
29+
return 0;
30+
}
31+
--final_safe_pos;
32+
}
33+
}
34+
++current_idx;
35+
}
36+
37+
38+
return final_safe_pos + 1;
39+
40+
}
41+
void swapElements(int* nums, int idx1, int idx2) {
42+
int temp = *(nums + idx1);
43+
*(nums + idx1) = *(nums + idx2);
44+
*(nums + idx2) = temp;
45+
return;
46+
}

0 commit comments

Comments
 (0)