Remove Element
来源:互联网 发布:cydia软件源福利 编辑:程序博客网 时间:2024/06/11 21:20
leetcode第27题,要求在一个数组中删除指定元素,而且要求是原地操作,不允许使用额外数组。
其实这个题目很明显使用双指针法,题目中hint还有一条是如果删除元素很稀少如何提高效率,我的思路是一头一尾进行遍历,头结点观察是否是指定删除的元素,如果是就要和把它放到末尾。这里分三种情况,一种是头指针为删除元素,尾指针为其余元素,则直接交换。如果头指针和尾指针都是要删除的元素,则要尾指针继续左移。其余情况下,头指针右移。
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ def swap(nums, i1, i2): tmp = nums[i1] nums[i1] = nums[i2] nums[i2] = tmp n = len(nums) start = 0 end = n-1 while start <= end: if nums[start] == val and nums[end] != val: swap(nums,start, end) start += 1 end -= 1 elif nums[start] == val and nums[end] == val: end -= 1 else: start += 1 return start
0 0
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Remove Element
- Struts2框架学习
- Python爬虫实战之爬取链家广州房价_03存储
- 刷题的日常[Leetcode]——9)Palindrom Number
- 如何访问远程服务器上的PHPMyAdmin
- android 监听网络状态的变化及实战
- Remove Element
- ViewPager,ScrollView 嵌套ViewPager滑动冲突解决
- Android 反射机制动态加载模块
- leetcode single number II
- html5 离线存储 地理信息与本地存储
- VC #include路径解析
- Android 性能优化系列之 App 启动优化
- 使用CoordinatorLayout打造各种炫酷的效果
- Eclipse 一直Building Workspace 的解决办法