题目


Given a sorted array nums, 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 1:

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

Example 2:

 Given nums = [0,0,1,1,1,2,2,3,3,4],

 Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.

 It doesn't matter what values are set beyond the returned length.

Clarification:

Confused why the returned value is an integer but your answer is an array?

Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well. Internally you can think of this:

// nums is passed in by reference. (i.e., without making a copy)
int len = removeDuplicates(nums);
// any modification to nums in your function would be known by the caller.
// using the length returned by your function, it prints the first len elements.
for (int i = 0; i < len; i++) {
print(nums[i]);
}

思路


双指针法

本题要返回一个有序数组内不重复元素的个数,要比较数组内两个元素是否相同,需要两个下标记录,于是想到双指针法。这里要注意两点:一是函数的形参是传引用,改变形参也会改变原本的数据;二是题目要求不得声明额外的空间。

对于一个有序数组,由于不能使用额外的空间保存删除重复元素后的数组,于是想到不删除重复元素,而是替换重复元素,将重复元素替换到后面,使用两个指针:

  • pBegin:记录不重复数组的最后一个元素的下标。

    • 遇到不重复元素时,pBegin加1,表示多了一个不重复元素。
  • pEnd:用于循环。
    • 当遇到重复元素时,pEnd加1
    • 当遇到不重复元素时,先pBegin加1,此时pBegin指向的还是重复元素,pEnd指向不重复元素。将pBegin所指元素与pEnd所指元素替换,此时pBegin指向不重复元素,并且下标代表不重复数组的最后一个下标;pEnd指向重复元素。

C++

class Solution {
public:
int removeDuplicates(vector<int>& nums) { if(nums.size() == 0)
return 0; int pBegin = 0;
int pEnd = 1; while(pEnd < nums.size()){
if(nums[pEnd] != nums[pBegin]){
pBegin ++;
nums[pBegin] = nums[pEnd];
}
pEnd ++;
}
return pBegin + 1; //从0计数的,因此长度+1
}
};

Python

最新文章

  1. fedora wine qq
  2. win10-golang环境变量设置
  3. 30个深度学习库:按Python、C++、Java、JavaScript、R等10种语言分类
  4. 根据JSON对象动态加载表格--大数据量
  5. Python装饰器(decorator)
  6. 【Spark学习】Apache Spark配置
  7. XML美化工具及其他各种美化工具
  8. 使用PHP把下划线分隔命名的字符串 转换成驼峰式命名方式 , 把下划线后面的第一个字母变成大写
  9. linux(readhat) yum源安装
  10. JavaScript 执行环境(执行上下文) 变量对象 作用域链 上下文 块级作用域 私有变量和特权方法
  11. 手机自动化测试:appium源码分析之bootstrap三
  12. 201521123108 《Java程序设计》第13周学习总结
  13. base64文件大小计算
  14. PHP类的反射和依赖注入
  15. mysql中用limit 进行分页有两种方式
  16. 复习java基础
  17. MySQL(2)---Explain
  18. SkyWalking-netcore
  19. Linux基础命令---显示登录用户logname
  20. matt cutts : try something new for 30 days

热门文章

  1. 【Linux】修改Linux操作系统字符集与Oracle数据库一致
  2. selenium菜单操作
  3. 虚拟机+linux+大杂烩
  4. Lazarus开发环境编译选项配置
  5. Python标准模块--logging(转载)
  6. windows10上安装mysql详细图文教程
  7. 将 GNOME 默认的界面切换动画功能关闭
  8. 连接mysql时遇到的问题
  9. eas之kdtable格式化
  10. 国庆day2