My LeetCode grinding. Trying to do a problem a day.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

main.c 994B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. void printArr(int* arr, int arrSize) {
  4. printf("[");
  5. for (int i = 0; i < arrSize; i++) {
  6. printf(" %d ", arr[i]);
  7. }
  8. printf("]\n");
  9. }
  10. int removeElement(int* nums, int numsSize, int val) {
  11. int endPointer = numsSize - 1;
  12. int i = 0;
  13. while (i < endPointer + 1) {
  14. if (nums[i] == val) {
  15. // Find a valid element to swap, if one is not found
  16. // then return the current length
  17. while (nums[endPointer] == val && endPointer > i) {
  18. endPointer--;
  19. }
  20. if (endPointer == i) {
  21. return i;
  22. }
  23. nums[i] = nums[endPointer--];
  24. }
  25. i++;
  26. }
  27. return i;
  28. }
  29. int main() {
  30. int* arr = malloc(sizeof(int) * 8);
  31. arr[0] = 0;
  32. arr[1] = 1;
  33. arr[2] = 2;
  34. arr[3] = 2;
  35. arr[4] = 3;
  36. arr[5] = 0;
  37. arr[6] = 4;
  38. arr[7] = 2;
  39. int result = removeElement(arr, 8, 2);
  40. printf("Expected: [ 0 1 4 0 3 ]\nGot: ");
  41. printArr(arr, result);
  42. return 0;
  43. }