zoukankan      html  css  js  c++  java
  • [面试真题] 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].

     1 class Solution {
     2 public:
     3     int removeDuplicates(int A[], int n) {
     4         // Start typing your C/C++ solution below
     5         // DO NOT write int main() function
     6         int tail  = 0;
     7         int rtn = n;
     8         for(int i=1; i<n; i++){
     9             while(i<n && A[i] == A[tail]){
    10                 i++;
    11                 rtn--;
    12             }
    13             A[++tail] = A[i];
    14         }
    15         return rtn;
    16     }
    17 };

    Run Status: Accepted!
    Program Runtime: 68 milli secs

    Progress: 160/160 test cases passed.
    !红色部分判定一开始没有加上,导致部分用例没能通过。
    [0,0,0,1,2,2,4,4]        输出:[0,1,2]
    [-3,-3,-2,-1,-1,0,0,0,0,0]      输出:[-3,-2,-1]
  • 相关阅读:
    linux-满足多字符条件统计行数
    oracle的面试问题
    在开发过程中为什么需要写存储过程
    面向对象编程
    动态SQL
    触发器

    子程序
    游标
    集合
  • 原文地址:https://www.cnblogs.com/infinityu/p/3076419.html
Copyright © 2011-2022 走看看