26. Remove Duplicates from Sorted Array - Easy

descrition

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 by modifying the input array in-place with O(1) extra memory.

Example

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 new length.

解析

注意题目的要求,in_place,即原址,不能借助额外的辅助空间。

再关注到另一个有利的前提条件,数组是有序的,因此重复的数字一定挨着,这是达到最优解的关键,时间复杂度 O(n)。

code


#include <vector>
#include <algorithm> using namespace std; class Solution{
public:
int removeDuplicates(vector<int>& nums){
if(nums.empty()) // don't forget the special case!!!!
return 0; int cur = 0; // the end of new nums
for(int i=1; i<nums.size(); i++){
if(nums[i] != nums[cur]){
nums[++cur] = nums[i];
}
} return cur+1; // return the new length
}
}; int main()
{
return 0;
}

最新文章

  1. 【Win 10应用开发】AdaptiveTrigger在自定义控件中是可以触发的
  2. Node.js入门笔记(1):基本概念
  3. c语言 &amp;取地址运算符的理解
  4. asp.net 操作word
  5. /bin/bash: [xxxx]: command not found
  6. 剑指OFFER之顺时针打印矩阵(九度OJ1391)
  7. REST Web 服务介绍
  8. 【最短路】【STL】CSU 1808 地铁 (2016湖南省第十二届大学生计算机程序设计竞赛)
  9. Error C1189: #error: Please use the /MD switch for _AFXDLL builds
  10. Pthon修炼5
  11. Python包管理工具和多版本环境管理
  12. PLT文件 和 DXF文件
  13. BZOJ 1426: 收集邮票 [DP 期望 平方]
  14. 一起学Hadoop——文件的上传、分发与打包
  15. 修改openssh显示版本号
  16. 黄聪:windows下使用xampp3.2.2配置多个监听端口和不同的网站目录
  17. log4j控制台乱码解决办法
  18. Trusted Block Chain Summit(2018.10.09)
  19. 【大数据】Hbase如何批量删除指定数据
  20. Java内存区域与虚拟机类加载机制

热门文章

  1. TYVJ P1153 间谍网络
  2. src/MD2.c:31:20: 错误:Python.h:没有那个文件或目录
  3. 洛谷 P1981 表达式求值
  4. Android开发经验一判断当前屏幕是全屏还是非全屏
  5. 虚拟机上的企业网络管理系统(cisco works 2000安装配置)
  6. iPad之Linux平台实践
  7. HDU 多校联合 6033 6043
  8. HDU 4631 Sad Love Story 平面内最近点对
  9. 1.字符设备驱动------Linux中断处理体系结构
  10. C#调用C++数组,结构体DLL