LeetCode80 : Remove Duplicates from Sorted Array II

Description

Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length.

Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.

Example1

 Given 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 respectively.
 It doesn't matter what you leave beyond the returned length.

解题思路

一边遍历一遍向前移动元素,不借助第三方变量

代码

class Solution {
    public int removeDuplicates(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }
        int i= 0;
        for( int n : nums) {
            if (i < 2 || n != nums[i - 2]) {
                nums[i ++] = n;
            }
        }
        return i;
    }
}

吐槽

这个题有点对不住 LeetCode medium 的难度

说点什么

avatar
  Subscribe  
提醒

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部