zoukankan      html  css  js  c++  java
  • [Leetcode 1] 26 Remove Duplicates from Sorted Array

    Problem:

    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]

    Analysis: 

    Use two pointers, ptrA always points to the last position of the no-dup array, ptrB traverse the original sorted array, once find an element not equal to *ptrA, increase ptrA and copy it to that position.

    The time complexity is O(n) and the sapce complexity is O(n)

    Code:

    public class Solution {
        public int removeDuplicates(int[] A) {
            // Start typing your Java solution below
            // DO NOT write main() function
            if (A.length == 0) return 0;
            
            int a = 0;
            for (int b=0; b<A.length; b++) {
                if (A[a] != A[b]) {
                    A[++a] = A[b];
                }
            }
            
            return (a+1);
        }
    }

    Special Attention:

    Pay attention to the special cases such as A is [], A is [1]

  • 相关阅读:
    洛谷 P1823 音乐会的等待
    [The Diary] 10.30 Monday
    洛谷 P1094 纪念品分组
    codevs 1258 关路灯
    NOIP 2012 国王游戏(60分)
    bzoj3745 [COCI2015]Norma
    CF1110E Magic Stones
    bzoj4237 稻草人
    bzoj2653 middle
    单调队列与斜率优化杂题
  • 原文地址:https://www.cnblogs.com/freeneng/p/leetcode_26.html
Copyright © 2011-2022 走看看