删除有序数组中的重复项
数组
题目
给你一个 升序排列 的数组 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];
}
如果所有断言都通过,那么您的题解将被 通过。
示例 1:
输入:nums = [1,1,2]
输出:2, nums = [1,2,_]
解释:函数应该返回新的长度 2 ,并且原数组 nums 的前两个元素被修改为 1, 2 。不需要考虑数组中超出新长度后面的元素。
示例 2:
输入:nums = [0,0,1,1,1,2,2,3,3,4]
输出:5, nums = [0,1,2,3,4]
解释:函数应该返回新的长度 5 , 并且原数组 nums 的前五个元素被修改为 0, 1, 2, 3, 4 。不需要考虑数组中超出新长度后面的元素。
提示:
1 <= nums.length <= 3 * 104
-104 <= nums[i] <= 104
nums 已按 升序 排列
Related Topics
数组
双指针
👍 3191
👎 0
class Solution {
public int removeDuplicates(int[] nums) {
}
}
思路
- 新建数组res,用来存储满足题意的结果
- 遍历两个数组,判断res的元素与nums元素是否相等,相等,nums下标+1,否则,都+1
实现
class Solution {
public int removeDuplicates(int[] nums) {
int[] res = new int[nums.length];
res[0] = nums[0];
int index=1;
for (int i=0;i<nums.length;i++){
if (nums[i]!=res[index-1]){
res[index] = nums[i];
index++;
}
}
for (int i=0;i<res.length;i++){
nums[i]=res[i];
}
return index;
}
}
结果
解答成功:
执行耗时:1 ms,击败了29.48% 的Java用户
内存消耗:42.9 MB,击败了74.45% 的Java用户
分析
- 两次for循环,其实是没必要的
- 直接修改原数组上的值,前
start
后end
两个指针,修改的位置指针index
,判断两个指针指向的值是否相等,不等就把位置指针的值修改成后指针的值,并且,前指针指向后指针,后指针+1; index
第0个位置不变,index
从第1个位置开始- 比较的时候,
start=0
与end=1
位置的值比较,相同就把end=1
的值放入index=1
的位置,start=end
&&end++
&&index++
优化1
class Solution {
public int removeDuplicates(int[] nums) {
if (nums==null) return 0;
if (nums.length<2) return nums.length;
int index=1;
int start =0;
int end = 1;
while (end!=nums.length){
if (nums[start]==nums[end]){
end++;
}
else {
nums[index]=nums[end];
start=end;
end++;
index++;
}
}
return index;
}
}
结果
解答成功:
执行耗时:0 ms,击败了100.00% 的Java用户
内存消耗:42.8 MB,击败了86.54% 的Java用户