LeetCode: Remove Duplicates from Sorted Array II

在上一题的基础上加了个bool twice,一次过

 1 class Solution {

 2 public:

 3     int removeDuplicates(int A[], int n) {

 4         // Start typing your C/C++ solution below

 5         // DO NOT write int main() function

 6         int dup = 0;

 7         bool twice = false;

 8         for (int i = 0; i < n-1; i++) {

 9             if (!twice) {

10                 if (A[i] == A[i+1]) twice = true;

11             }

12             else {

13                 while (A[i] == A[i+1] && i+dup < n-1) {

14                     dup++;

15                     for (int j = i; j < n-dup; j++) A[j] = A[j+1];

16                 }

17                 twice = false;

18             }

19         }

20         return n - dup;

21     }

22 };

 C#

 1 public class Solution {

 2     public int RemoveDuplicates(int[] nums) {

 3         int dup = 0;

 4         int n = nums.Length;

 5         bool twice = false;

 6         for (int i = 0; i < n-1; i++) {

 7             if (!twice) {

 8                 if (nums[i] == nums[i+1]) twice = true;

 9             }

10             else {

11                 while (nums[i] == nums[i+1] && i + dup < n - 1) {

12                     dup++;

13                     for (int j = i; j < n - dup; j++) nums[j] = nums[j+1];

14                 }

15                 twice = false;

16             }

17         }

18         return n - dup;

19     }

20 }
View Code

 

你可能感兴趣的:(LeetCode)