题目:
原题链接:Remove Duplicates from Sorted Array
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.
int removeDuplicates(int* nums, int numsSize) {
if (numsSize == 0)
return 0;
int i = 0;
int rest = 0;
int first = nums[0];
for (i = 0; i < numsSize; i++) {
if (nums[i] != first){
rest++;
first = nums[i];
nums[rest] = nums[i];
}
}
return rest + 1;
}时间排名:
本文介绍了一种在不使用额外空间的情况下从有序数组中去除重复元素的方法,并提供了一个C语言实现的例子。该方法通过遍历数组并只保留不重复的元素来达到目的,最终返回新的有效长度。

228

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



