• LeetCode80 Remove Duplicates from Sorted Array II


    题目:

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

    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.

    分析:

    仍然采用Remove Duplicates from Sorted Array I 中的双指针思路,只不过增加一个变量count记录出现的次数,两次以内的仍然可以添加的数组中。

    代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(vector<int>& nums) {
     4         if (nums.size() == 0) {
     5             return 0;
     6         }
     7         int count = 0, p = 1;
     8         for (int i = 1; i < nums.size(); ++i) {
     9             if (nums[i] == nums[i - 1]) {
    10                 if (count < 1) {
    11                     nums[p] = nums[i];
    12                     p++;
    13                 }
    14                 count++;
    15             }
    16             else {
    17                 nums[p] = nums[i];
    18                 p++;
    19                 count = 0;
    20             }
    21         }
    22         return p;
    23     }
    24 };
     
  • 相关阅读:
    Operator开发实例
    Go构建HTTP服务
    Go依赖包的管理
    Go并发编程机制
    Go语言的基础数据类型
    k8s的APIServer流程介绍
    promise、resolve、reject、拦截响应
    AngularJS中service,factory,provider的区别
    scope
    sass入门
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5922168.html
Copyright © 2020-2023  润新知