Remove Duplicates from Sorted Array
Easy 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
最后更新于
这有帮助吗?
Easy 原题链接:https://leetcode.com/problems/remove-duplicates-from-sorted-array/
最后更新于
这有帮助吗?
原题链接:
Given a sorted array nums, remove the duplicates 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 with O(1) extra memory.
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.
注意
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.
使用index,在原数组上做remove
或者
分析:
T=O(n), S=O(1)
使用STL的distance和unique
关于distance:
Calculates the number of elements between first and last.
关于unique:
Removes all but the first element from every consecutive group of equivalent elements in the range [first,last)
.
分析:
根据STL中unique是使用双指针实现的:
改写unique,使用upper_bound
分析:
题目开始,联想到快慢指针的方法。如果对STL熟悉,可以想到unique函数来进行解题,但是题目提示为sorted array,所以unique的解法不一定是最优解。在理解unique的原理和分析题目的基础上,作出变形改写。