LeetCode
26 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.
解答
时间复杂度:O(n)
空间复杂度:O(1)
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if (n <= 1)
return n;
int tail = 1;
for (int i = 1; i < n; i++)
{
if(nums[tail - 1] != nums[i])
nums[tail++] = nums[i];
}
return tail;
}
};

本文介绍了解决LeetCode中关于去除有序数组中重复元素的问题,使用时间复杂度为O(n)且空间复杂度为O(1)的方法进行实现。
1106

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



