Leetcode - Remove Duplicates from Sorted Array II

Leetcode - Remove Duplicates from Sorted Array II_第1张图片

My code:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int del = 0;
        int count = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                count++;
                if (count > 2)
                    del++;
                else
                    nums[i - del] = nums[i];
            }
            else {
                count = 1;
                nums[i - del] = nums[i];
            }
        }
        return nums.length - del;
    }
    
    public static void main(String[] args) {
        Solution test = new Solution();
        int[] a = {1, 1, 1, 1, 3, 3};
        System.out.println(test.removeDuplicates(a));
    }
}

My test result:

Leetcode - Remove Duplicates from Sorted Array II_第2张图片

这次作业不难,主要是直接看了此题的简单版本的代码,以前做过。然后有了思路。这题变形在,允许最多出现两次,那么就用一个count来计数就行了,超过两次就开始删除。然后不超过又相等的话,这里就有个细节,就需要不停地往前移,往前覆盖。

**
总结: Array, two pointer
**

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0)
            return 0;
        int del = 0;
        int counter = 1; // used to record the number of elements with same values
        /** traverse the whole array */
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                if (counter >= 2) {
                    del++; // if count >= 2, increase del by 1 
                }
                else {
                    nums[i - del] = nums[i]; // if not, move repetive element to front
                }
                counter++; // count the repetive elements
            }
            else {
                nums[i - del] = nums[i];
                counter = 1; // resotre counter
            }
        }
        return nums.length - del;
    }
}

差不多的做法,没什么好说的。

Anyway, Good luck, Richardo!

My code:

public class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        
        int del = 0;
        int counter = 1;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i - 1]) {
                counter++;
                if (counter > 2) {
                    del++;
                }
                else {
                    nums[i - del] = nums[i];
                }
            }
            else {
                counter = 1;
                nums[i - del] = nums[i];
            }
        }
        
        return nums.length - del;
    }
}

差不多的解法。

Anyway, Good luck, Richardo! -- 09/04/2016

你可能感兴趣的:(Leetcode - Remove Duplicates from Sorted Array II)