1 Remove duplicates from Sorted Array II
Follow "Remove duplicates": What if duplicates is allowed at most twice? For Example,given sorted array nums = [1,1,1,2,2,3],
Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3. It doesn ' t matter what are you leave beyond the new length.
Unlike deleting duplicate elements, this removes only the parts that have more than 2 duplicates. As with removing duplicate elements, it's just that the number of flags with one tag is more than 2.
intRemoveDuplicates ( vector<int>& Nums) {intN=nums.size ();if(n==0)return 0;intLength=0;BOOLflag=false; for(intI=1; i<n;i++) {if(Nums[length]!=nums[i]) {nums[length+1]=nums[i]; length++; flag=false; }Else{if(!flag) {flag=true; nums[length+1]=nums[i]; length++; } } }returnlength+1; }
2 Remove duplicates from Sorted List II
Given a sorted linked list, delete all nodes that has duplicate numbers, leaving only distinct numbers from the original List. For example:
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
Because the same element is all deleted, the first pointer to the list may be deleted, so you must use the head pointer to the first node of the list.
ListNode*Deleteduplicates (ListNode*Head) {if(Head==NULL)return NULL; ListNode*Result=NewListNode (0); Result -Next=Head ListNode*Or:=Result ListNode*Cur=Head while(cur) {if(cur -Next&&Cur -Val==Cur -Next -val) {int value=Cur -Val while(cur -Next&&Value==Cur -Next -Val) {//delete duplicate elements other than the first elementListNode*Mid=Cur -Next Cur -Next=Mid -Next Delete mid; } ListNode*T=Cur Cur=T -Next Delete T;//Delete First repeating elementPre -Next=Cur }Else{Pre=Cur Cur=Cur -Next } }returnResult -Next }
Leetcode's Medium collection (C + + implementation) 16