TypechoJoeTheme

IT技术分享

统计

[LeetCode 80] Remove Duplicates from Sorted Array II [Java]

2018-03-10
/
0 评论
/
794 阅读
/
正在检测是否收录...
03/10

1. Description

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

2. 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 1, 1, 2, 2 and 3. It doesn't matter what you leave beyond the new length.

3. Code

public class LeetCode0080 {
    public int removeDuplicates(int[] nums) {
        if(nums == null || nums.length == 0) {
            return 0;
        }
        int pre = 0;
        int count = 1;
        for(int i = 1; i< nums.length; i++) {
            if(nums[i] == nums[pre]) {
                if(count >= 2) {
                    continue;
                }else {
                    count ++;
                }
            }else {
                count = 1;
            }
            nums[++ pre] = nums[i];
        }
        return pre + 1;
    }

    public static void main(String[] args) {
        LeetCode0080 leetcode = new LeetCode0080();
        System.out.println(leetcode.removeDuplicates(new int[] {1,1,1,2,2,3}));
    }
}
Array
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/1470/(转载时请注明本文出处及文章链接)