leetcode之 Remove Duplicates from Sorted Array
来源:互联网 发布:哪个贷款软件最靠谱 编辑:程序博客网 时间:2024/05/06 06:34
题目:
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.
解答:
找到第一个比当前大的数,放到当前的后面,如此下去即可,注意下一次寻找的时候可以不用从当前开始寻找,直接从上一次找到的位置开始就可以,因为数组已经是sorted的了,这样复杂度是O(n),从当前开始寻找复杂度是O(n^2),然而在跑的时间上却没什么区别,看来leetcode的测试数据并没有那种很刁钻的
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int size = nums.size();
if(size == 0)
return 0;
if(size == 1)
return 1;
int pos = 0;
//int end = size - 1;
int findStart = pos + 1;
while(true)
{
bool find = false;
for(int j = findStart;j < size;++j)
{
if(nums[j] > nums[pos])
{
find = true;
int t = nums[j];
nums[j] = nums[pos + 1];
nums[pos + 1] = t;
pos++;
findStart = j + 1;
}
}
if(!find)
break;
}
return pos + 1;
}
};
- leetcode之Remove Duplicates from Sorted Array
- LeetCode 之 Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- 【LeetCode】之Remove Duplicates from Sorted Array
- leetcode之Remove Duplicates from Sorted Array
- 【Leetcode】之Remove Duplicates from Sorted Array
- leetcode之 Remove Duplicates from Sorted Array
- LeetCode 之 Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- LeetCode之Remove Duplicates from Sorted Array II
- Leetcode之四Remove Duplicates from Sorted Array II
- LeetCode之Remove Duplicates from Sorted Array II
- 【BZOJ】3339 - Ⅲ - 变式Ⅱ+变式Ⅲ
- 最短寻道时间优先算法(SSTF)
- struts2简单好用的自定义日期转换
- 1036
- calendar工具包
- leetcode之 Remove Duplicates from Sorted Array
- java nio对OP_WRITE的处理解决网速慢的连接
- Android Material Design之Toolbar与Palette实践
- leetcode215---Kth Largest Element in an Array(第k大元素)
- 序列化与编辑器
- hdu 1166 敌兵布阵
- 数组循环移位算法
- javascript性能优化——懒加载提升代码效率
- 敏捷开发框架Srum实例