Given a sorted array, remove the duplicates in place such, all element appear only once and return the new L Ength.
Do the allocate extra space for another array, and you must does this on place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function should return length = 2
, with the first of the elements of nums being and 1
2
Respectivel Y. It doesn ' t matter what are you leave beyond the new length.
1. Simple algorithm
intRemoveDuplicates (int* Nums,intnumssize) { inti =0; intj =1; intK =0; if(Numssize <2) returnnumssize; 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++; } returni;}
- Submission Result:time Limit exceeded more Details
- Last executed input:[-999,-999,-998,-998,-997,-997,-996,-996,-995,-995,-994,-994,-993,-993,-992,-992,-991,-991,- 990,-990,-989,-989,-988,
- As if the input can be 1, so the same value is set to-1, the method itself is not feasible
2, with the link list time complexity of O (n^2)
typedefstructnode{intdata; structNode *next;}*node, *LIST;intInsertlist (LIST L,intnum) {NODE tmp=NULL; while(L->next! =NULL) {L= l->Next; if(L->data = =num) { return 0; }} tmp= (NODE)malloc(sizeof(structNode)); if(TMP = =NULL) { return-1; } tmp->data =num; TMP->next =NULL; L->next =tmp; return 1;}intRemoveDuplicates (int* Nums,intnumssize) {inti =0; LIST Root= (LIST)malloc(sizeof(structNode)); Root->data =0; Root->next =NULL; for(inti =0; i < numssize; i++) {insertlist (root, nums[i]); } I=0; while(Roo->nextt! =NULL) {Root= root->Next; Nums[i]= root->data; I++; } returni;}
- It's still a reminder of the complexity of the time.
3. Online Solutions
int removeduplicates (int * nums, Span style= "COLOR: #0000ff" >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;}
- Originally I read the wrong topic, people only need to connect the same value to remove, and do not need to filter out all the same ....
Remove Duplicates from Sorted Array