From c78db7989d3777607df903edf7ae7592cf24ff72 Mon Sep 17 00:00:00 2001 From: begeekmyfriend Date: Sun, 1 Oct 2017 09:31:16 +0800 Subject: [PATCH] Remove duplicates from sorted array Signed-off-by: begeekmyfriend --- .../Makefile | 2 ++ .../rm_dup.c | 36 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 026_remove_duplicates_from_sorted_array/Makefile create mode 100644 026_remove_duplicates_from_sorted_array/rm_dup.c diff --git a/026_remove_duplicates_from_sorted_array/Makefile b/026_remove_duplicates_from_sorted_array/Makefile new file mode 100644 index 0000000..5cf5932 --- /dev/null +++ b/026_remove_duplicates_from_sorted_array/Makefile @@ -0,0 +1,2 @@ +all: + gcc -O2 -o test rm_dup.c diff --git a/026_remove_duplicates_from_sorted_array/rm_dup.c b/026_remove_duplicates_from_sorted_array/rm_dup.c new file mode 100644 index 0000000..092b457 --- /dev/null +++ b/026_remove_duplicates_from_sorted_array/rm_dup.c @@ -0,0 +1,36 @@ +#include +#include + +static int removeDuplicates(int* nums, int numsSize) +{ + if (numsSize <= 1) { + return numsSize; + } + + int i = 0, j, count = 1; + while (i < numsSize) { + for (j = i + 1; j < numsSize && nums[i] == nums[j]; j++) {} + if (j < numsSize) { + nums[count++] = nums[j]; + } + i = j; + } + + return count; +} + +int main(int argc, char **argv) +{ + int i, size = argc - 1; + int *nums = malloc(size * sizeof(int)); + for (i = 0; i < argc - 1; i++) { + nums[i] = atoi(argv[i + 1]); + } + + int count = removeDuplicates(nums, size); + for (i = 0; i < count; i++) { + printf("%d ", nums[i]); + } + printf("\n"); + return 0; +}