原题:
Given a sorted array nums, 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 by modifying the input array in-place with O(1) extra memory.
Example 1:
Given 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 returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five
elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by
the caller.
// using the length returned by your function, it prints the
first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}
翻译:
给你一个排好序的数组 nums,就地删除重复项,使每个元素只出现一次并返回新的长度。
不要分配额外的数组空间, 你必须通过使用O(1)的额外内存修改输入数组来实现。
例 1:
Given nums = [1,1,2],
你的函数需要返回length = 2, 而且nums前两个元素分别为1,2.
你数组的长度可以超过返回的长度.
例 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
你的函数需要返回 length = 5, 而且前nums前五个
元素分别为 0, 1, 2, 3, 和 4 .
你数组的长度可以超过返回的长度.
解释:
为什么返回的值是整数,但您的答案是数组?
注意:输入数组是通过引用传入的,这意味着调用方也将知道对输入数组的修改。.
你可以这么认为:
// nums是通过引用传入的. (i.e., 不是通过复制)
int len = removeDuplicates(nums);
// 你在函数中对nums的任何修改调用者都会知道
// 输出你返回长度的前几个元素
for (int i = 0; i < len; i++) {
print(nums[i]);
}
C程序
int removeDuplicates(int* nums, int numsSize){
if(numsSize == 0)return 0;
int index = 1;
for (int i =0; i<numsSize-1;++i)
{
if(nums[i] != nums[i+1])
{
nums[index] = nums[i+1];
++index;
}
}
return index;
}

本文介绍了一种在不使用额外空间的情况下,从已排序数组中去除重复元素的方法,通过一个简单的C程序实现,该程序将数组修改为只包含唯一元素,并返回新长度。
309

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



