From 5a3738ac080025514eef12872a8e0614cab85276 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Tue, 12 Sep 2017 09:37:27 +0800 Subject: [PATCH] Remove duplicates from sorted array Signed-off-by: begeekmyfriend --- .../Makefile | 2 ++ .../rm_dups.c | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 080_remove_duplicates_from_sorted_array_ii/Makefile create mode 100644 080_remove_duplicates_from_sorted_array_ii/rm_dups.c diff --git a/080_remove_duplicates_from_sorted_array_ii/Makefile b/080_remove_duplicates_from_sorted_array_ii/Makefile new file mode 100644 index 0000000..863c440 --- /dev/null +++ b/080_remove_duplicates_from_sorted_array_ii/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test rm_dups.c diff --git a/080_remove_duplicates_from_sorted_array_ii/rm_dups.c b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c new file mode 100644 index 0000000..6156057 --- /dev/null +++ b/080_remove_duplicates_from_sorted_array_ii/rm_dups.c @@ -0,0 +1,33 @@ +#include +#include + +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"); +}