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.
题目要求在不申请额外数组空间的情况下删除数组中的重复元素,即空间复杂度为 O(1),个人思路是:
- 设置一前一后两个下标索引 idx 和 i,i 用来遍历数组,idx 用来标识当前需要判断是否重复的数字的值(idx 始终小于 i,因为和自身比较没有意义);
- 初始化 idx 为 0,i 为 1;
- 判断传入数组长度 size,若 size 小于 2,返回 size,程序结束;否则执行下一步;
- 比较 num[idx] 和 num[i],如果不相等,则 ++idx 移动到下一个新的位置保存新值;
- ++i 进行下一个元素检验,如果 i < size,执行步骤 4;否则,返回 idx + 1,程序结束。
int removeDuplicates(int* nums, int numsSize) {
int i;
int idx;
if (numsSize < 2) {
return numsSize;
}
for (i = 1, idx = 0; i != numsSize; ++i) {
if (nums[idx] != nums[i]) {
nums[++idx] = nums[i];
}
}
// idx 是下标索引,最终返回的是实际数组的长度
return (idx + 1);
}
网友评论