LeetCode初级算法练习
2018-03-29 22:25
381 查看
26. 从排序数组中删除重复项给定一个有序数组,你需要原地删除其中的重复内容,使每个元素只出现一次,并返回新的长度。不要另外定义一个数组,您必须通过用 O(1) 额外内存原地修改输入的数组来做到这一点。示例:给定数组: nums = [1,1,2],
你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2
不需要理会新的数组长度后面的元素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.
你的函数应该返回新长度 2, 并且原数组nums的前两个元素必须是1和2
不需要理会新的数组长度后面的元素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.
class Solution: def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int 前提是已排序 判断nums[j]与nums[i-1]元素,相等j+1继续判断下一元素;不相等,nums[j]赋值给nums[i], 返回i与size的最小值(size为0时返回size,没有不相同的时候 size==i,有相同的i<size) """ i = 1 j = 1 size = len(nums) while j < size: if nums[j] == nums[i-1]: j += 1 else: nums[i] = nums[j] i += 1 j += 1 return min(i,size)
相关文章推荐
- 算法练习 - leetcode
- 『LeetCode』练习第四弹_算法6题
- 『LeetCode』练习第六弹_算法9题
- 算法练习专题——LeetCode系列之 ThreeSum
- 『LeetCode』练习第五弹_算法7,8题
- 『LeetCode』练习第二弹_算法3,4题
- LeetCode 算法练习 Compare Version Numbers
- 常见算法练习leetcode
- leetcode演练算法-----mit学习算法,,学习和练习相得益彰
- 常见算法练习leetcode
- leetcode外的算法题练习总结(updating)(自言自语)
- 常见算法练习leetcode
- 算法练习专题——LeetCode系列之 Two Sum
- leetcode 算法练习 two-sum
- 『LeetCode』练习第一弹_算法1,2题
- 算法练习_LeetCode_链表1
- 『LeetCode』练习第三弹_算法5题
- 【慢慢学算法】:位运算练习
- 【python】【leetcode】【算法题目344—Reverse String】
- 算法练习:两指针之三数之和为0