12345678910111213141516171819202122232425262728293031323334353637383940414243444546 |
- #include <stdio.h>
- #include <stdlib.h>
-
- void printArr(int* arr, int arrSize) {
- printf("[");
- for (int i = 0; i < arrSize; i++) {
- printf(" %d ", arr[i]);
- }
- printf("]\n");
- }
-
- int removeElement(int* nums, int numsSize, int val) {
- int endPointer = numsSize - 1;
- int i = 0;
- while (i < endPointer + 1) {
- if (nums[i] == val) {
- // Find a valid element to swap, if one is not found
- // then return the current length
- while (nums[endPointer] == val && endPointer > i) {
- endPointer--;
- }
- if (endPointer == i) {
- return i;
- }
- nums[i] = nums[endPointer--];
- }
- i++;
- }
- return i;
- }
-
- int main() {
- int* arr = malloc(sizeof(int) * 8);
- arr[0] = 0;
- arr[1] = 1;
- arr[2] = 2;
- arr[3] = 2;
- arr[4] = 3;
- arr[5] = 0;
- arr[6] = 4;
- arr[7] = 2;
- int result = removeElement(arr, 8, 2);
- printf("Expected: [ 0 1 4 0 3 ]\nGot: ");
- printArr(arr, result);
- return 0;
- }
|