leetcode 【 Remove Duplicates from Sorted Array 】python 实现
2024-08-27 11:42:38
题目:
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 A = [1,1,2]
,
Your function should return length = 2
, and A is now [1,2]
.
代码:oj测试通过 Runtime: 143 ms
class Solution:
# @param a list of integers
# @return an integer
def removeDuplicates(self, A):
if len(A) == 0:
return 0 curr = 0
for i in range(0, len(A)):
if A[curr] != A[i] :
A[curr+1],A[i] = A[i],A[curr+1]
curr += 1
return curr+1
思路:
首先排除长度为0的special case
使用双指针技巧:用curr指针记录不含有重复元素的数据长度;另一个指针i从前往后走
Tips: 注意curr是数组元素的下标从0开始,所以再最后返回时要返回curr+1
最新文章
- RabbitMQ Step by step(一) 安装
- 简论:int i = 0
- android学习笔记40——国际化和资源自适应
- js判断小数点几位
- Android(java)学习笔记136:Java类初始化顺序
- android初级应用到高端架构教程------ 完整体系化学习android开发
- Android 的独特shell命令
- Unity3D 预备知识:C#与Lua相互调用
- Android Studio 首坑 Gradle sync failed: Cause: error in opening zip file 的错误
- 【转】深入探讨 Java 类加载器
- eclipse没有联想功能的解决办法
- JAVA 的 Date、Calendar的常用用法
- 学JAVA的第十九天,抽象类注意事项
- python数据处理excel和pdf,并打包成exe
- centos7防火墙设置
- [12]Windows内核情景分析 --- MDI
- python中 cmp
- 1083 矩阵取数问题(DP)
- R语言中聚类确定最佳K值之Calinsky criterion
- Angular2快速入门-4.创建一个服务(创建NewsService提供数据)