Skip to content

Commit

Permalink
Remove duplicates from sorted array
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Sep 12, 2017
1 parent 2a1e4c0 commit 5a3738a
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 080_remove_duplicates_from_sorted_array_ii/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test rm_dups.c
33 changes: 33 additions & 0 deletions 080_remove_duplicates_from_sorted_array_ii/rm_dups.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
#include <stdio.h>
#include <stdlib.h>

int removeDuplicates(int* nums, int numsSize) {
int i = 0, j, x, y, count = 0;
while (i < numsSize) {
for (j = i + 1; j < numsSize && nums[i] == nums[j]; j++) {}
int diff = j - i;
if (diff > 2) {
for (x = i + 2, y = j; y < numsSize; x++, y++) {
nums[x] = nums[y];
}
numsSize -= diff - 2;
}
count += diff > 2 ? 2 : diff;
i += diff > 2 ? 2 : diff;
}
return count;
}

int main(int argc, char **argv)
{
int i, count = argc - 1;
int *nums = malloc(count * sizeof(int));
for (i = 0; i < count; i++) {
nums[i] = atoi(argv[i + 1]);
}
count = removeDuplicates(nums, count);
for (i = 0; i < count; i++) {
printf("%d ", nums[i]);
}
printf("\n");
}

0 comments on commit 5a3738a

Please sign in to comment.