zoukankan      html  css  js  c++  java
  • LeetCode: Remove Duplicates from Sorted Array

    LeetCode: Remove Duplicates from Sorted Array

    Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

    Do not allocate extra space for another array, you must do this in place with constant memory.

    For example,
    Given input array A = [1,1,2],

    Your function should return length = 2, and A is now [1,2].

    地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array/

    算法:直接看代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         if(n <= 1)  return n;
     5         int j = 1;
     6         for(int i = 1; i < n; ++i){
     7             if(A[i] != A[i-1]){
     8                 A[j++] = A[i];
     9             }
    10         }
    11         return j;
    12     }
    13 };

    第二题:

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

    For example,
    Given sorted array A = [1,1,1,2,2,3],

    Your function should return length = 5, and A is now [1,1,2,2,3].

    地址:https://oj.leetcode.com/problems/remove-duplicates-from-sorted-array-ii/

    算法:每个元素至少可以有两个。遍历的过程中统计每一个元素出现的次数,然后最多留下其中的两个。代码:

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         if(!A || n <= 2)  return n;
     5         int j = 0;
     6         int i = 0;
     7         while(i < n){
     8             int count = 1;
     9             while(i + count < n && A[i+count] == A[i]){
    10                 ++count;
    11             }
    12             A[j++] = A[i++];
    13             --count;
    14             if(count){
    15                 A[j++] = A[i++];
    16                 --count;
    17             }
    18             i += count;
    19         }
    20         return j;
    21     }
    22 };
  • 相关阅读:
    pip安装
    nfs
    源码方式安装软件
    自启动
    multipath
    linux永久添加和删除路由
    iscsi
    linux识别workstation磁盘的uuid
    centos镜像各种cd,dvd版本区别
    转:C# 中 MSCHART 饼状图显示百分比
  • 原文地址:https://www.cnblogs.com/boostable/p/leetcode_remove_duplicates_from_sorted_array.html
Copyright © 2011-2022 走看看