80. Remove Duplicates from Sorted Array II

题目:

Follow up for "Remove Duplicates":
What if duplicates are allowed at most twice?

For example,
Given sorted array nums = [1,1,1,2,2,3],

Your function should return length = 5, with the first five elements of nums being 1122 and 3. It doesn't matter what you leave beyond the new length.

 

Hide Tags
  Array Two Pointers
 

链接:  http://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

题解:

在排好序的数组里最多保留两个重复数字。设置一个limit,使用一个count,一个result用来计算最终结果。依照count和limit的关系决定是否移动到下一个index。

Time Complexity - O(n), Space Complexity - O(1)。

public class Solution {

    public int removeDuplicates(int[] nums) {

        if(nums == null || nums.length == 0)

            return 0;            

        int limit = 2, count = 1, result = 0;

        

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

            if(i > 0 && nums[i] == nums[i - 1])

                count ++;

            else

                count = 1;

            if(count <= limit)

                nums[result ++] = nums[i];

        }

        return result;

    }

}

 

测试:

你可能感兴趣的:(remove)