zoukankan      html  css  js  c++  java
  • leetcode Remove Duplicates from Sorted Array II

     1 /*****************************************************************
     2 created:    2014/09/13 16:16
     3 filename:    remove-duplicates-from-sorted-array.cpp
     4 author:        Justme0 (http://blog.csdn.net/justme0)
     5 
     6 purpose:    有序数组中,有至少三个相同元素时删掉只留两个
     7 https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
     8 *****************************************************************/
     9 
    10 #include <iostream>
    11 #include <cassert>
    12 #include <vector>
    13 using namespace std;
    14 
    15 class Solution {
    16 public:
    17     int removeDuplicates(int A[], int n) {
    18         if (n <= 2) {
    19             return n;
    20         }
    21 
    22         vector<int> iVec;
    23         iVec.push_back(A[0]);
    24         for (int i = 1; i < n - 1; ++i) {
    25             if (!(A[i - 1] == A[i] && A[i] == A[i + 1])) {
    26                 iVec.push_back(A[i]);
    27             }
    28         }
    29         iVec.push_back(A[n - 1]);
    30 
    31         assert(iVec.size() <= unsigned(n));
    32         for (unsigned i = 0; i < iVec.size(); ++i) {
    33             A[i] = iVec[i];
    34         }
    35 
    36         return iVec.size();
    37     }
    38 };
    39 
    40 class Solution2 {
    41 public:
    42     int removeDuplicates(int A[], int n) {
    43         if (n <= 2) {
    44             return n;
    45         }
    46 
    47         int len = 2;
    48         for (int i = 2; i < n; ++i) {
    49             if (A[i] != A[len - 2]) {
    50                 A[len] = A[i];
    51                 ++len;
    52             }
    53         }
    54         assert(len <= n);
    55 
    56         return len;
    57     }
    58 };
    59 
    60 int main(int argc, char **argv) {
    61     int arr[] = {1, 1, 2, 2, 3};
    62     int len = sizeof arr / sizeof *arr;
    63     int new_len = Solution2().removeDuplicates(arr, len);
    64     for (int i = 0; i < new_len; ++i) {
    65         cout << arr[i] << endl;
    66     }
    67 
    68     system("PAUSE");
    69     return 0;
    70 }
  • 相关阅读:
    控制器生命周期逻辑调用
    数据持久化
    Mac屏幕录制Gif
    iOS开发应用上架必读最新苹果审核规则
    过滤字符串中的非汉字、字母、数字
    文字加描边
    博客全局修改需求
    iOS Xcode12 运行iOS15系统程序卡在启动页要等很久才能进入主页
    macOS环境:安装Go(21-10-22完)
    关闭WIN10自动配置 IPV4 地址 169.254解决方法
  • 原文地址:https://www.cnblogs.com/jjtx/p/3970368.html
Copyright © 2011-2022 走看看