Remove Duplicates from Sorted Array
2015-08-02 15:23
423 查看
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 =
Your function should return length =
It doesn't matter what you leave beyond the new length.
简单的双指针问题。class Solution {
public:
//双指针
void Swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if (len < 2)
return len;
int low = 0, high = 1;
while (high < len)
{
if(nums[high] != nums[low])
Swap(nums[++low], nums[high]);
++high;
}
return low + 1;
}
};
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
1and
2respectively.
It doesn't matter what you leave beyond the new length.
简单的双指针问题。class Solution {
public:
//双指针
void Swap(int &a, int &b)
{
int tmp = a;
a = b;
b = tmp;
}
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if (len < 2)
return len;
int low = 0, high = 1;
while (high < len)
{
if(nums[high] != nums[low])
Swap(nums[++low], nums[high]);
++high;
}
return low + 1;
}
};
相关文章推荐
- javascript add event remove event
- IE不支持option的display样式,只能使用remove和add
- jquery使用remove()方法删除指定class子元素
- Lua的table库函数insert、remove、concat、sort详细介绍
- MongoDB Remove函数的3个常见用法
- jquery之empty()与remove()区别说明
- ASP.NET之Response.Cookies.Remove 无法删除COOKIE的原因
- Datatable删除行的Delete和Remove方法的区别介绍
- jQuery中remove()方法用法实例
- FR子接口使用解析
- FR详解
- jQuery方法区别(七)detach() remove()区别
- jQuery方法区别(七)detach() remove()区别
- 删除List里面元素的时候抛出UnsupportedOperationException异常
- 优先队列(堆)--二叉堆学习笔记
- 把 ad 里面的用户加入到moss 网站 ,然后分配权限
- ABAP-内表
- SAP abap SELECT *
- pku1002题解
- C语言分布式系统中的进程标识