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.
Subscribe to see which companies asked this question
#include<iostream>
#include<vector>
using namespace std;
class Solution{
public:
int removeDuplicates(vector<int>& nums){
int n = nums.size();
int index = 0;
if (n == 0) return 0;
for (int i = 1; i < n; i++){
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};
int main()
{
vector<int> nums1 = { 1, 1,1};
Solution sol;
int n1 = sol.removeDuplicates(nums1);
cout << n1 << endl;
system("pause");
return 0;
}

本文介绍了一个高效的算法,用于在不使用额外空间的情况下移除已排序数组中的重复元素,并返回新的长度。通过一次遍历和比较相邻元素的方式实现,确保了常数级别的内存使用。
586

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



