删除有序数组中的重复项
给你一个 升序排列 的数组
nums
,请你 原地 删除重复出现的元素,使每个元素 只出现一次 ,返回删除后数组的新长度。元素的 相对顺序 应该保持 一致 。然后返回nums
中唯一元素的个数。考虑
nums
的唯一元素的数量为k
,你需要做以下事情确保你的题解可以被通过:
- 更改数组
nums
,使nums
的前k
个元素包含唯一元素,并按照它们最初在nums
中出现的顺序排列。nums
的其余元素与nums
的大小不重要。- 返回
k
。判题标准:
系统会用下面的代码来测试你的题解:
int[] nums = [...]; // 输入数组 int[] expectedNums = [...]; // 长度正确的期望答案 int k = removeDuplicates(nums); // 调用 assert k == expectedNums.length; for (int i = 0; i < k; i++) { assert nums[i] == expectedNums[i]; }如果所有断言都通过,那么您的题解将被 通过。
方法一
class Solution {
public int removeDuplicates(int[] nums) {
if (nums.length <= 1) {
return nums.length;
}
// 二分检索
int index = 0;
for (int i = 0; i < nums.length; i++) {
if (!searchElement(nums, nums[i], (i + 1))) {
nums[index] = nums[i];
index++;
}
}
return index;
}
public boolean searchElement(int[] nums, int ele, int startIndex) {
if (nums == null || nums.length == 0) {
return false;
}
int begin = startIndex;
int end = nums.length;
while (begin < end) {
int mid = (begin + end) >> 1;
if (ele < nums[mid]) {
end = mid;
} else if (ele > nums[mid]) {
begin = mid + 1;
} else {
return true;
}
}
return false;
}
}
时间复杂度 T(n) = O(nlogn)
方法二
class Solution {
public int removeDuplicates(int[] nums) {
int n = nums.length;
if (n == 0) {
return 0;
}
int fast = 1, slow = 1;
while (fast < n) {
if (nums[fast] != nums[fast - 1]) {
nums[slow] = nums[fast];
++slow;
}
++fast;
}
return slow;
}
}
时间复杂度 T(n)= O(n)
空间复杂度 O(1)