LeetCode之Remove Duplicates from Sorted Array II

简介: LeetCode之Remove Duplicates from Sorted Array II

1、题目

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


2、代码实现

public class Solution {

   public int removeDuplicates(int[] nums) {

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

     return 0;

    }

    int length = nums.length;

    int newLen = 1;

    int count = 1;

    for (int i = 1; i < length; ++i) {

     if (nums[i] == nums[i - 1]) {

      count++;

      if (count <= 2) {

       nums[newLen++] =  nums[i];

      }

     } else {

      count = 1;

      nums[newLen++] = nums[i];

     }

    }

       return newLen;

   }

}

3、总结

既然看到连续相等,那我们就要想到前后两个不相等作为条件,然后加上通过一个变量不超过2个就可以了


相关文章
|
6月前
Leetcode 4. Median of Two Sorted Arrays
题目描述很简单,就是找到两个有序数组合并后的中位数,要求时间复杂度O(log (m+n))。 如果不要去时间复杂度,很容易就想到了归并排序,归并排序的时间复杂度是O(m+n),空间复杂度也是O(m+n),不满足题目要求,其实我开始也不知道怎么做,后来看了别人的博客才知道有个二分法求两个有序数组中第k大数的方法。
16 0
|
6月前
Leetcode Find Minimum in Rotated Sorted Array 题解
对一个有序数组翻转, 就是随机取前K个数,移动到数组的后面,然后让你找出最小的那个数,注意,K有可能是0,也就是没有翻转。
20 0
Search in Rotated Sorted Array - 循环有序数组查找问题
Search in Rotated Sorted Array - 循环有序数组查找问题
51 0
LeetCode 167 Two Sum II - Input array is sorted(输入已排序数组,求其中两个数的和等于给定的数)
给定一个有序数组和一个目标值 找出数组中两个成员,两者之和为目标值,并顺序输出
58 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
|
算法 Python
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
LeetCode 108. 将有序数组转换为二叉搜索树 Convert Sorted Array to Binary Search Tree
|
算法 测试技术
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 88. 合并两个有序数组 Merge Sorted Array
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
LeetCode 21. 合并两个有序链表 Merge Two Sorted Lists
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
LeetCode 19. 删除链表的倒数第N个节点 Remove Nth Node From End of List
存储 算法 C语言
10 1

热门文章

最新文章