Remove Duplicates from Sorted Array [python解]
来源:互联网 发布:薛之谦淘宝店不开了吗 编辑:程序博客网 时间:2024/05/22 09:04
题目要求:Givena sorted array, remove the duplicates in place such that each element appearonly once and return the new length.
Do not allocate extra spacefor another array, you must do this in place with constant memory.
For example,
Given input array nums = [1,1,2]
,
Your function shouldreturnlength = 2
,with the first twoelements of nums being 1
and 2
respectively. It doesn't matter what you leave beyond the newlength.
大致意思:给定一个已经排序好的列表,把其中重复元素移除使列表中元素唯一并且返回新列表长度。不允许再额外创建列表,必须在原有的输入列表上改动。
这一题因为自己没准确理解题意,走了不少岔路,写下自己思考过程与大家交流。
题目解析:这一题看题目都能看懂,关键是对原列表的处理和返回不重复列表的长度值的理解,这里的‘remove’并不是真正从原列表中移除,例子最后说 ‘It doesn't matterwhat you leave beyond the new length’,超出不重复元素长度的部分不用在意,又加上题目不允许开辟额外空间,故不可用删除重复元素改变原列表长度的方法解题。例子上我加粗部分,已经明确说明,需返回不重复列表元素的长度(例子中不重复元素有2个),并且此返回的列表是位于原列表的前面部分(即返回的nums前2个元素就是不重复的元素)。
题目输出要求归纳:
1.结果应返回不重复元素个数length;
2.原列表nums的元素排列前length个元素应唯一且升序,之后元素不做要求。
解题思路:遍历列表,以nums[0]为基准,下标指针j为0,逐一与后面元素比较找出不等元素,将不等元素放到第二个元素的位置nums[1],此时j+1,再以nums[1]为基准找出下一个不等元素,以此类推将不等元素放至nums列表的前面部分。返回j+1即为不重复列表长度,结果显示的不重复的列表则为截断nms列表的前j+1个元素。
代码实现:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ #此题因为不允许开辟额外空间,所以不推荐使用删除重复元素。而选择将不重复元素放在原列表开头,返回新列表长度,截取原列表即可。 if len(nums) == 0: return 0 j = 0 len_n = len(nums) for i in range(len_n): if nums[j] != nums[i]: nums[j + 1] = nums[i] j += 1 return j + 1
所以,深刻理解题意非常重要!
- Remove Duplicates from Sorted Array [python解]
- [leetcode] Remove Duplicates from Sorted Array python
- 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
- Leetcode-Remove Duplicates from Sorted Array-Python
- 【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates From Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Remove Duplicates from Sorted Array
- Java_基础—将文本反转
- SSH免密登陆
- Java IO 字节流 字符流操作
- 魅族手机AudioRecord报错。
- 官方及自定义线程池
- Remove Duplicates from Sorted Array [python解]
- 列向量和行向量看待矩阵乘法
- Bayes公式解释
- hdu 2433 Travel(Dijkstra+思维)
- 数组遍历 和 迭代器遍历的区别
- python_yield
- 部署zinnia的问题
- 剪切子文件夹下的文件到当前文件夹的bat文件
- 遇到org.apache.ibatis.exceptions.PersistenceException: ### Error querying database. Cause: java.sql.