Remove Duplicates from Sorted Array python 题解
来源:互联网 发布:android程序员校招 编辑:程序博客网 时间:2024/06/04 22:48
Remove Duplicates from Sorted Array python 题解
题意描述:
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].
给定一个排好序的数组,去掉重复的元素,只让相同的元素只出现一次,返回新数组的长度
题目有个要求就是不允许开辟新的数组空间
分析思路
这道题类似实现C++ 中的去重操作,大致思路是遍历一遍数组将所有重复元素取第一个依次放到数组的最前面,然后截取数组的前半段即可
具体实现:遍历数组,用start记录遇到的每次遇到第一个重复元素要调整到的位置:这里start初值为1而不是0,因为新数组的第一个元素和旧数组是一样的,用keyValue记录遇到的重复元素,遍历数组,每次遇到新的重复元素,则更新keyValue,然后将该元素放到start指示的位置上,然后start向后挪一位,最后把原数组前半段没有重复元素的部分作为新数组(题目要求必须进行截取,否则WA),此时start的值就是新数组长度。
Python代码实现如下:
class Solution: # @param a list of integers # @return an integer def removeDuplicates(self, A): if A==[]: return 0 start=1;keyValue=A[0];length=len(A) for i in range(length): if A[i]!=keyValue: keyValue=A[i] A[start]=A[i] start+=1 A=A[:start] return start
0 0
- Remove Duplicates from Sorted Array python 题解
- LeetCode题解:Remove Duplicates from Sorted Array
- [LeetCode]Remove Duplicates from Sorted Array题解
- [leetcode] Remove Duplicates from Sorted Array python
- Remove Duplicates from Sorted Array [Python]
- 26. Remove Duplicates from Sorted Array (python)
- 26. Remove Duplicates from Sorted Array-Python
- Remove Duplicates from Sorted Array [python解]
- Leetcode-Remove Duplicates from Sorted Array-Python
- 【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
- LeetCode题解:Remove Duplicates from Sorted Array I and II
- leetcode 题解 || Remove Duplicates from Sorted Array 问题
- Remove Duplicates from Sorted Array---leetcode 我的java题解
- LeetCode题解——Remove Duplicates from Sorted Array
- LeetCode 题解(162): Remove Duplicates from Sorted Array II
- LeetCode 题解(163): Remove Duplicates from Sorted Array
- Leetcode题解14 26. Remove Duplicates from Sorted Array
- LeetCode 26 Remove Duplicates from Sorted Array题解
- python字符编码显示中文
- 教育类网站备案需要办理前置审批,蓝队网络帮助您
- 自定义标签
- Linux下最简单的FTP服务器搭建方法
- Pushlet 简单实现
- Remove Duplicates from Sorted Array python 题解
- POJ 1523——Tarjan + 计算删除割点后的连通分支数
- Axis2webservice发布
- table方法也属于模型类的连贯操作方法之一,主要用于指定操作的数据表。
- 索引式优先队列(indexed priority queue)
- struts2 从一个action 跳转到另一个action的两种方法
- 点击左侧菜单在右侧弹出相应的内容
- IOS公司开发者账号申请详细教程
- Java Awt和Swing是的关系以及区别