[LeetCode26] Remove Duplicates from Sorted Array
2016-06-01 18:56
435 查看
作为LeetCode:80的先导题,不会做80的先看这题。
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.
Subscribe to see which companies asked this question
C++实现:
从头往后依次比较,遇到不同的就把他放到前面,若要得到最后的数组结果 可以使用 nums.resize(index+1).
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0)
return 0;
int index = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};
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
1and
2respectively.
It doesn't matter what you leave beyond the new length.
Subscribe to see which companies asked this question
C++实现:
从头往后依次比较,遇到不同的就把他放到前面,若要得到最后的数组结果 可以使用 nums.resize(index+1).
class Solution {
public:
int removeDuplicates(vector<int>& nums) {
if (nums.size() == 0)
return 0;
int index = 0;
for (int i = 0; i < nums.size(); i++)
{
if (nums[index] != nums[i])
nums[++index] = nums[i];
}
return index + 1;
}
};
相关文章推荐
- 第十一周项目训练5
- 精确计算工具类,提供加减乘除的计算
- 第13周项目2:动物这样叫(3)
- UIDynamic物理仿真 属性方法解释(一篇就OK)
- UVA oj 10071 Back to High School Physics(简单数学)
- HTML5 Web Workers
- 第13周项目4-立体类族共有的抽象类
- struts2实现批量上传和打包批量下载
- Public Function MyReplace(rng As Range
- Android APP报毒和排查解决
- Ubuntu下安装Qt环境及Qt Creator开发工具
- Structural Patterns Part 1/7: Adapter Pattern
- 编译器和解释器,预编译和预处理
- 怎么把一个int数组转化为char型数组??
- javascript:算法之数组去重
- Hiredis 基本使用
- [LeetCode 80]Remove Duplicates from Sorted Array II
- JavaScript设计模式之接口
- 【框架】App运行过程解析
- SQL Server2012请验证实例名是否正确并且SQL Server 已配置为允许远程连接。error40等。。