题目内容

本题来源于LeetCode

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.

题目思路

本题难度等级: easy

本题要求的是原地进行处理,而且不能够申请新的空间。本题采用的方法是数组当中非常常见的处理方法:快慢指针。

方法是:分别设立两个指针index,i。初始情况下,index和i都指向数组的第一个元素。i为快指针,index为慢指针。 i从第一个元素一直扫描到最后一个元素。index是慢指针,仅当nums[i]!=nums[index]的时候,index才会自增1。当扫描结束的时候,index指向的是不重复数组的最后一个元素,其长度为index+1

Python代码

class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if not A:
return 0
index= 0
for i in range( len(A)):
if A[i] != A[index]:
index+= 1
A[index] = A[i]
return index+ 1

最新文章

  1. ionic ios 发布设置 header-bar高度无效
  2. [Android] 深入浅出Android App耗电量统计
  3. GAT2.0使用文档(组合接口测试)
  4. redis 安装及相关问题解决
  5. 第六章 - 图像变换 - 图像拉伸、收缩、扭曲、旋转[2] - 透视变换(cvWarpPerspective)
  6. FineReader Mac如何设置参数让导出为DOCX/RTF/ODT格式
  7. checkbox与文字的间距
  8. windows下的python扩展包下载地址
  9. HDOJ2024C语言合法标识符
  10. leetcode—triangle
  11. Scala闭包
  12. 统计功能和子对象的大小信息查询Bug
  13. TFS 如何恢复到指定版本
  14. poj 3177
  15. JQuery 拖动层
  16. String VS Cstring(字符串)
  17. ionic2 使用 cordova 打包成安卓apk
  18. mysql对binlog的处理
  19. MySql 中文乱码解决办法
  20. Scala编程快速入门系列(一)

热门文章

  1. 用Markdown优雅的写文章
  2. C# 模拟跑马灯效果(2种)
  3. Linux内核的基本概念
  4. Linux 安装依赖库
  5. 一个Ruby静态代码分析器 rubocop
  6. Django 学习笔记(二)
  7. 水题 第三站 HDU Largest prime factor
  8. Vuejs——v-on
  9. java String/StringBuilder 方法
  10. Java试题