0%

[0026] Remove Duplicates From Sorted Array

Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.

Test Case

Given When Then
nums = [1,1,2] Remove Duplicates From Sorted Array return 2
nums = [0,0,1,1,1,2,2,3,3,4] Remove Duplicates From Sorted Array return 5

Solution

1. Double Pointer

通过快慢指针遍历数组,当重复时前移快指针跳过重复,当不重复时前移慢指针并赋值,直到到达数组末尾。

1
2
3
4
5
6
7
8
9
10
11
12
public int removeDuplicates(int[] nums) {
if (nums.length == 0) {
return 0;
}
int i = 0;
for (int j = 1; j < nums.length; j++) {
if (nums[i] != nums[j]) {
nums[++i] = nums[j];
}
}
return i + 1;
}

复杂度分析

  • 时间复杂度: O(n)

    假设数组长度为n,那么最多执行N步,因此时间复杂度为 O(n)。

  • 空间复杂度: O(1)

    该算法中存储空间大小固定,因此空间复杂度为 O(1)

-------------本文结束感谢您的阅读-------------