LeetCode: Remove Duplicates from Sorted Array

很奇怪这种小问题会多数次过。。太小看他了

 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         for (int i = 0; i < n-1-dup; i++) {

 8             if (A[i] != A[i+1]) continue;

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

10             dup++;

11             i--;

12         }

13         return n-dup;

14     }

15 };

 下面段代码更好

 1 class Solution {

 2 public:

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

 4         if (n < 2) return n;

 5         int c = 0;

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

 7             if (A[c] != A[i]) A[++c] = A[i];

 8         }

 9         return c+1;

10     }

11 };

 C#

 1 public class Solution {

 2     public int RemoveDuplicates(int[] nums) {

 3         if (nums.Length < 2) return nums.Length;

 4         int c = 0;

 5         for (int i = 0; i < nums.Length; i++) {

 6             if (nums[c] != nums[i]) nums[++c] = nums[i];

 7         }

 8         return c + 1;

 9     }

10 }
View Code

 

你可能感兴趣的:(LeetCode)