[LeetCode] 26 - Remove Duplicates from Sorted Array
2015-08-28 10:48
381 查看
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 =
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
size_t size = nums.size();
if (size <= 1) {
return size;
}
int j = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i -1]) {
continue;
}
nums[++j] = nums[i];
}
return (j + 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:
int removeDuplicates(vector<int>& nums) {
size_t size = nums.size();
if (size <= 1) {
return size;
}
int j = 0;
for (int i = 1; i < nums.size(); ++i) {
if (nums[i] == nums[i -1]) {
continue;
}
nums[++j] = nums[i];
}
return (j + 1);
}
};
相关文章推荐
- 915 +-字符串【贪心+模拟】
- 存储过程循环loop
- Android之——史上最简单旋转菜单实现效果
- oldssoj1107奶牛浴场(最大子矩阵)
- 为什么程序员有高薪却不高兴?
- 4个独立按键实现对数码管数字显示的加减清零等
- char (*)[]无法传给参数char **
- ffmpeg_function: av_sample_get_buffer_size
- jQuery实现的Div窗口震动效果实例
- 打开Word时出现“The setup controller has encountered a problem during install. Please ...”
- Android layout布局属性、标签属性总结大全
- 谈谈关于GCD相关问题
- 更改ORACLE所占用的8080端口号
- 详解C语言的exp()函数和ldexp()函数以及frexp()函数
- 通过Oracle.DataAccess.dll访问vs2008报ORA-12560错误
- vim config
- Android 悬浮窗的实现源码
- [刷题]Add Two Numbers
- C++栈和队列
- poj1305毕达哥拉斯三元组