题目:

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.

题解:

  感觉这个题是真没什么好解析的。。。

Solution 1()

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
if(n < )
return n;
int index = ;
for(int i = ; i < n; ++i)
if(nums[index] != nums[i])
nums[++index] = nums[i];
return index + ;
}
};

Solution 2()

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int n = nums.size();
int count = ;
for(int i = ; i < n; i++){
if(A[i] == A[i-]) count++;
else A[i-count] = A[i];
}
return n-count;
}
};

Solution 3

class Solution {
public:
int removeDuplicates(vector<int>& nums) {
int len = nums.size();
if (len <= ) {
return ;
}
int prev = , cur = ;
while (cur < len) {
if (nums[cur] == nums[prev]) {
++cur;
} else if (cur != prev + ){
nums[++prev] = nums[cur++];
} else {
++prev;
++cur;
}
}
return prev + ;
}
};

为了避免多余的复制操作,可以扩展使用,比如类数组,当数组没有重复对象时,无需复制操作。而之前的两个解答将会依次复制。

最新文章

  1. 转:详解Eclipse断点
  2. ROS语音交互——科大讯飞语音合成TTS(二)
  3. rabbitmq 相关方法
  4. Shared Library Search Paths
  5. c++ 全局变量初始化的一点总结
  6. [ERROR] Plugin &#39;InnoDB&#39; init function returned error
  7. 实现WMSservice的时候,出现边缘的点或icon被切断的情况
  8. 车牌识别LPR(八)-- 字符识别
  9. sql server where、group by、order by 执行顺序
  10. Gamit解算脚本
  11. 禁止chrome中CORS跨域资源共享错误
  12. ASP.Net中使用Report Service
  13. Java面试题精选(三) JSP/Servlet Java面试逻辑题
  14. 从零使用Python测试。Testing Using Python.
  15. [转载]binlog归档
  16. struts2简单入门-数据校验
  17. vue+vux页面滚动定位(支持上下滑动)
  18. Jenkins入门-环境搭建(1)
  19. js动态添加未知新属性
  20. hdu 2005 求第几天(水题)

热门文章

  1. iOS开发系列--让你的应用“动”起来【转载】
  2. Nginx与Apache的Rewrite规则的区别
  3. 数据库ACID操作---事务四原则
  4. CI去掉 URL 中的 index.php
  5. 【BZOJ4514】[Sdoi2016]数字配对 费用流
  6. EasyNVR流媒体服务器接入EasyDSS云视频平台快照上传实现
  7. scrapy架构解析
  8. process_thread_action
  9. php总结3——基本函数、流程控制中的循环
  10. Redis之java增删改查