给定一个排序数组,你需要在 原地 删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在 原地 修改输入数组 并在使用 O(1) 额外空间的条件下完成
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
示例1:
示例2:
提示:
Java解法
package sj.shimmer.algorithm.ten_2;
/**
* Created by SJ on 2021/2/10.
*/
class D17 {
public static void main(String[] args) {
int[] nums = {1, 1, 2};
System.out.println(removeDuplicates(nums));
for (int num : nums) {
System.out.println(num);
}
}
public static int removeDuplicates(int[] nums) {
if (nums==null||nums.length==0) {
return 0;
}
int real = 0;
for (int i = 0; i < nums.length; i++) {
if (i == 0) {
real = i;
} else {
if (nums[i] != nums[real]) {
real++;
nums[real] = nums[i];
}
}
}
return real+1;
}
}
官方解
-
双指针
时间复杂度:O(n)
空间复杂度:O(1)