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. // Remove Duplicates from Sorted Array
  2. // 时间复杂度O(n),空间复杂度O(1)
  3. class Solution {
  4. public int removeDuplicates(int[] nums) {
  5. if (nums.length == 0) return 0;
  6. int index = 1;
  7. for (int i = 1; i < nums.length; i++) {
  8. if (nums[i] != nums[index-1])
  9. nums[index++] = nums[i];
  10. }
  11. return index;
  12. }
  13. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/array/remove-duplicates-from-sorted-array.html