LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
来源:互联网 发布:impress.js demo 编辑:程序博客网 时间:2024/06/10 03:19
LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
26. Remove Duplicates from Sorted Array [Easy]
题目: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 by modifying the input array in-place with O(1) extra memory.
Example:
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 new length.
这个问题即将 list 中不重复的元素按照原有的顺序排起来并返回 list 中不同数值的数量,注意这里要求原位操作,所以必须 O(1) 的空间复杂度。这样我们将每次检测到的与之前不同的值(如 example 中检测到一个2)应当放在之前那个值(即第一个1)所在位置的后一个位置,然后更新要比较的值(更新为2)继续比较,知道遍历完所有元素。emmm。。。这次机制的我吸取教训,先判断是不是特殊情况,如果为空list,直接返回0 。代码如下:
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if nums == []: return 0 idx = 0 for item in nums: if not item == nums[idx]: idx = idx + 1 nums[idx] = item return idx + 1
尽量减少变量名,取 list 元素for循环直接取不要用下标取。结果如下:
总结:
时间复杂度线性,空间复杂度常数。这个题比较简单,没啥好总结的。
THE END
2017/12/16 Sat 16:26
阅读全文
0 0
- LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
- leetcode笔记:Remove Duplicates from Sorted Array
- [leetcode][array] Remove Duplicates from Sorted Array
- 【Leetcode】【Array】Remove Duplicates from Sorted Array
- leetcode笔记:Remove Duplicates from Sorted Array II
- LeetCode笔记:26. Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- leetcode 35: Remove Duplicates from Sorted Array
- [LeetCode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array
- Leetcode: Remove Duplicates from Sorted Array
- [leetcode] Remove Duplicates from Sorted Array II
- PTA一周练(第一周)记录
- 链表操作之删除重复元素
- Hdoj 2668 Daydream
- jzoj3577 [CEOI2011]Traffic 强连通分量缩点
- Java多线程系列--【基础篇07】- 线程休眠
- LeetCode小白菜笔记[8]:Remove Duplicates from Sorted Array
- leetcode 518. Coin Change 2 动态规划DP
- html5-服务端数据推送简记
- 成员变量与局部变量的区别:
- 2017-2018noip复习计划
- STM32启动过程解读与跟踪验证
- python读conf配置文件--ConfigParser
- 热门微信小程序demo源码下载汇总(17/12.8-15)
- The Experiment Detail for Article