题目原文:
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 nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
题目大意:
给一个按序排列好的数组,在原位上删除相同元素,只留下一个,并返回新的长度。
不要使用新空间。
例如,原数组为[1,1,2]则返回2,并把原数组修改为[1,2].在新长度以后的数字是不用考虑的。
题目分析:
吸取上题经验之后,使用双指针,其中“指针”i代表当前扫描的位置,“指针”count指向要插入的位置。每次比较i和i-1下标对应元素是否相同,若相同则i是冗余的,直接跳过,否则count指针对应元素记录下来当前数值,并右移count。i扫完后count就代表不重复数字的个数。
源码:(language:java)
public class Solution {
public int removeDuplicates(int[] A) {
int len = A.length;
if (len == 0)
return 0;
int count = 1;
for (int i = 1; i < len; i++) {
if (A[i] != A[i - 1])
A[count++] = A[i];
}
return count;
}
}
成绩:
1ms,beats 54.30%,众数2ms,46.31%
cmershen的碎碎念:
本题的i“指针”是与i-1作比较,因此i从1开始遍历以防止数组越界。
严格而言,i和count是int类型,而不是指针(int*类型),且java中没有指针。但i和count起到了类似于C语言指针的作用。
本文介绍了一种在原地删除有序数组中重复元素的方法,通过双指针技巧实现,其中一个指针用于扫描数组,另一个指针用于记录不重复元素的位置。文章提供了Java实现代码,并分析了其效率。
264

被折叠的 条评论
为什么被折叠?



