【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
来源:互联网 发布:四剑圣2.6优化版攻略 编辑:程序博客网 时间:2024/06/10 00:09
Remove Duplicates from Sorted Array
题目大意
对排好序的list去重,输出去重后长度,并且不能创建新的数组
解题思路
使用一个指针j,当i向后遍历数组时,如果遇到与A[j]不同的,将A[i]和A[j+1]交换,同时j=j+1,即j向后移动一个位置,然后i继续向后遍历。
代码(我提交的)
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ j = 0 for i in range(len(nums)): if nums[i] == nums[j]: i += 1 continue else: nums[j+1] = nums[i] i += 1 j += 1 nums = nums[:j+1] return len(nums)
Remove Duplicates from Sorted Array II
题目大意
在 Remove Duplicates from Sorted Array(从一个有序的数组中去除重复的数字,返回处理后的数组长度) 的基础上,可以使每个数字最多重复一次,也就是说如果某一个数字的个数大于等于2个,结果中应保留2个该数字。
解题思路
参考:http://www.cnblogs.com/zuoyuan/p/3783453.html
使用两个指针prev和curr,判断A[curr]是否和A[prev]、A[prev-1]相等,如果相等curr指针继续向后遍历,直到不相等时,将curr指针指向的值赋值给A[prev+1]。
代码
class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <= 2: return len(nums) prev = 1 curr = 2 while curr < len(nums): # print 'curr:', nums[curr], 'prev, prev-1:', nums[prev], nums[prev - 1] if nums[curr] == nums[prev] and nums[curr] == nums[prev - 1]: curr += 1 else: prev += 1 # print 'fu zhi gei prev hou de yi wei:', nums[prev], nums[curr] nums[prev] = nums[curr] curr += 1 return prev + 1
总结
网上答案思路统一,代码不尽相同,python有个set()函数可以用来去重,不过结果一直有误,例如:[1,1,2]输出为[1,1],没自己研究,比较忙最近,有空的时候好好看一下set()
阅读全文
0 0
- 【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- LeetCode: Remove Duplicates from Sorted Array II
- [Leetcode] Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- [LeetCode]Remove Duplicates from Sorted Array II
- [leetcode]Remove Duplicates from Sorted Array II
- LeetCode-Remove Duplicates from Sorted Array II
- [leetcode] Remove Duplicates from Sorted Array II
- LeetCode - Remove Duplicates from Sorted Array II
- LeetCode:Remove Duplicates from Sorted Array II
- LeetCode | Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- 【leetcode】Remove Duplicates from Sorted Array II
- Leetcode: Remove Duplicates from Sorted Array II
- [LeetCode] Remove Duplicates from Sorted Array II
- OS X 系统自带的截图快捷键
- lua 人机交互(一)
- 判断素数的俩种方法
- Android Senser 使用方式
- js禁用浏览器后退功能、自动刷新页面
- 【Leetcode】【python】Remove Duplicates from Sorted Array/Remove Duplicates from Sorted Array II
- 统计文本中某些词出现的次数
- 【剑指offer】面试题4:二维数组的查找
- Python eval函数
- 设计模式--观察者模式
- 有趣的宏定义
- ES6 函数的参数设置默认值
- docker之windows10安装步骤
- 二叉树的先序递归创建和遍历