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]
  • 相关阅读:
    053-606
    053-605
    1019 General Palindromic Number (20分)
    1208. 翻硬币
    754. 平方矩阵 II
    1346. 回文平方
    680. 剪绳子
    1227. 分巧克力
    756. 蛇形矩阵
    429. 奖学金
  • 原文地址:https://www.cnblogs.com/infinityu/p/3076419.html
Copyright © 2011-2022 走看看