[Algo] 115. Array Deduplication I

Given a sorted integer array, remove duplicate elements. For each group of elements with the same value keep only one of them. Do this in-place, using the left side of the original array and maintain the relative order of the elements of the array. Return the array after deduplication.

Assumptions

  • The array is not null

Examples

  • {1, 2, 2, 3, 3, 3} → {1, 2, 3}

public class Solution {
  public int[] dedup(int[] array) {
    // Write your solution here.
   // return array;
    if (array == null || array.length <= 1) {
      return array;
    }
    int slow = 0;
    // result include slow
    for (int i = 1; i < array.length; i++) {
      if (array[i] == array[slow]) {
        continue;
      }
      array[++slow] = array[i]; 
    }
    return Arrays.copyOf(array, slow + 1);
  }
}

 

public class Solution {
  public int[] dedup(int[] array) {
    // Write your solution here.
   // return array;
    if (array == null || array.length <= 1) {
      return array;
    }
    int slow = 1;
    for (int i = 1; i < array.length; i++) {
      if (array[i] == array[slow - 1]) {
        continue;
      }
      array[slow++] = array[i]; 
    }
    return Arrays.copyOf(array, slow);
  }
}

 

posted @ 2020-02-24 00:13  xuan_abc  阅读(174)  评论(0编辑  收藏  举报