zoukankan      html  css  js  c++  java
  • 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 public class Solution {
     2     public int removeDuplicates(int[] A) {
     3         // Note: The Solution object is instantiated only once and is reused by each test case.
     4         if(A == null || A.length == 0) return 0;
     5         if(A.length == 1) return 1;
     6         int start = 0;
     7         for(int i = 0; i < A.length; i ++){
     8             if(A[i] != A[start]){
     9                 A[++start] = A[i];
    10             }
    11         }
    12         return ++start;
    13     }
    14 }

    第三遍:

     1 public class Solution {
     2     public int removeDuplicates(int[] A) {
     3         if(A == null || A.length == 0) return 0;
     4         int len = 0;
     5         for(int i = 1; i < A.length; i ++){
     6             if(A[i] != A[len]){
     7                 len ++;
     8                 A[len] = A[i];
     9             }
    10         }
    11         return len + 1;
    12     }
    13 }
  • 相关阅读:
    HDU 3081 Marriage Match II
    HDU 4292 Food
    HDU 4322 Candy
    HDU 4183 Pahom on Water
    POJ 1966 Cable TV Network
    HDU 3605 Escape
    HDU 3338 Kakuro Extension
    HDU 3572 Task Schedule
    HDU 3998 Sequence
    Burning Midnight Oil
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3896214.html
Copyright © 2011-2022 走看看