标签:
Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?
For example,
Given sorted array A = [1,1,1,2,2,3]
,
Your function should return length = 5
, and A is now [1,1,2,2,3]
.
Array Two Pointers
这题与leetcode_26题——Remove Duplicates from Sorted Array (string)这道题差不多,设置两个指针i和j,j是从前往后遍历,若遇到与前面不同的则将j坐标的A[j]给前面A[i+1],然后将i+1,即前面的指针才往后移一位,这样依次往后,到最后的时候,i+1的值即为数组后来结果的大小,只是需要考虑可以容忍最多有两个相同的数字
#include<iostream> using namespace std; int removeDuplicates(int A[], int n) { if(n==0) return 0; if(n==1) return 1; if(n==2) return 2; int i=1; int j=2; while(j<n) { if(A[j]!=A[j-1]) { if(j!=(i+1)) { A[i+1]=A[j]; i++; j++; } else { i++; j++; } } else { if(A[i]==A[i-1]&&A[i]==A[j]) j++; else { if(j!=(i+1)) { A[i+1]=A[j]; i++; j++; } else { i++; j++; } } } } return i+1; } int main() { int A[4]={1,2,2,2}; cout<<removeDuplicates(A,4)<<endl; int n1=removeDuplicates(A,4); for(int i=0;i<n1;i++) cout<<A[i]<<endl; }
leetcode_80题——Remove Duplicates from Sorted Array II(两个指针)
标签:
原文地址:http://www.cnblogs.com/yanliang12138/p/4458164.html