Leetcode: Remove Duplicates from Sorted Array
设置一个游标, 记录最后一个不重复的元素
代码:
#include <iostream> using namespace std; class Solution { public: int removeDuplicates(int A[], int n) { if(n==0) return 0; int cursor = 0; for(int i = 1; i < n; i ++) { if(A[i] == A[cursor]) { continue; }else{ if(i == cursor+1) cursor++; else A[++cursor] = A[i]; } } return cursor+1; } };
与上题略有不同
#include <iostream> using namespace std; class Solution { public: int removeElement(int A[], int n, int elem) { int cursor = 0; for(int i = 0; i < n; i ++) { if(A[i] != elem) { A[cursor++] = A[i]; } } return cursor; } };