标签:
Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first two elements of nums being 1
and 2
respectively. It doesn‘t matter what you leave beyond the new length.
1、朴素算法
int removeDuplicates(int* nums, int numsSize) { int i = 0; int j = 1; int k = 0; if(numsSize < 2) return numsSize; while (i < numsSize) { for (; j < numsSize; j++) { if (nums[i] == nums[j]) nums[j] = -1; } i++; while (nums[i] == -1) i++; j = i + 1; } i = 1; j = 2; while (j < numsSize) { while(nums[j] == -1) j++; nums[i] = nums[j]; i++; j++; } return i; }
typedef struct Node { int data; struct Node *next; }*NODE, *LIST; int insertList(LIST l, int num) { NODE tmp = NULL; while (l->next != NULL) { l = l->next; if (l->data == num) { return 0; } } tmp = (NODE)malloc(sizeof(struct Node)); if (tmp == NULL) { return -1; } tmp->data = num; tmp->next = NULL; l->next = tmp; return 1; } int removeDuplicates(int* nums, int numsSize) { int i = 0; LIST root = (LIST)malloc(sizeof(struct Node)); root->data = 0; root->next = NULL; for (int i = 0; i < numsSize; i++) { insertList(root, nums[i]); } i = 0; while (roo->nextt != NULL) { root = root->next; nums[i] = root->data; i++; } return i; }
3、网上解答
int removeDuplicates(int* nums, int numsSize) { if(!numsSize) return 0; int num=1,i; for(i=1;i<numsSize;++i) {if(nums[i]!=nums[i-1]) nums[num++]=nums[i]; } return num; }
Remove Duplicates from Sorted Array
标签:
原文地址:http://www.cnblogs.com/dylqt/p/4834480.html