Remove Element
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] = tmpn = len(nums)start = 0end = n-1while start <= end:if nums[start] == val and nums[end] != val:swap(nums,start, end)start += 1end -= 1elif nums[start] == val and nums[end] == val:end -= 1else:start += 1return start
Remove Element相关推荐
- LeetCode算法入门- Remove Element -day20
LeetCode算法入门- Remove Element -day20 1. 题目描述 Given an array nums and a value val, remove all instance ...
- [LeetCode] Remove Element 分析
Remove Element算是LeetCode的一道水题,不过这题也有多种做法,现就我所知的几种做一点讨论. 题目链接:https://leetcode.com/problems/remove-el ...
- LeetCode OJ:Remove Element(移除元素)
Given an array and a value, remove all instances of that value in place and return the new length. T ...
- [LeetCode] Remove Element
代码: 1 1 class Solution { 2 2 public: 3 3 int removeElement(int A[], int n, int elem) { 4 4 int index ...
- LeetCode Remove Element
Given an array and a value, remove all instances of that value in place and return the new length. T ...
- Leetcode: Remove Element
称号: Given an array and a value, remove all instances of that value in place and return the new lengt ...
- 【LeetCode从零单排】No27.Remove Element
题目 Given an array and a value, remove all instances of that value in place and return the new length ...
- leetcode 27. Remove Element
问题描述: Given an array and a value, remove all instances of that value in-place and return the new len ...
- Leet Code OJ 27. Remove Element [Difficulty: Easy]
题目: Given an array and a value, remove all instances of that value in place and return the new lengt ...
- LeetCode之Remove Element
1.题目 Given an array and a value, remove all instances of that value in place and return the new leng ...
最新文章
- 【特效】移入显示移出隐藏
- android ui自动化测试工具,介绍Robotium+Orange实现androidUI自动化测试
- python学不会的表情包-python这么简单 为何这么多人学不会
- proxool java_Java应用中使用Proxool
- assets目录与res/raw目录下文件的区别
- 在二元树中找出和为某一值的所有路径
- 通过url判断当前页,动态给导航加样式
- dbutils mysql_使用DBUtils控制mysql事务
- 关于tomcat不能启动的问题(NB:JAVA_HOME should point to a JDK not a JRE)
- python基于大数据的招聘信息实时数据分析系统的设计与实现
- Activiti6详细教程
- 华硕台式计算机编号,怎么查看华硕电脑设备序列号
- 2021-2025年中国电源管理IC(PMIC)行业市场供需与战略研究报告
- 系统工程师 运维工程师区别
- 2021辽宁省大学生程序设计竞赛(C、D、E、F、G、L)
- 计算机毕业设计SSM电脑配件仓储后台管理系统【附源码数据库】
- PyTorch之填充操作
- Snell法则的推导
- 计算机上的查找替换功能快速格式化,Excel 2016中使用查找替换功能应用技巧
- 考研复试专业课面试——C++
热门文章
- 关于高德地图问题总结 (二)地理围栏的使用
- 清华大学计算机博后,科学网—我在清华做博士后的收获 - 喻海良的博文
- 深入理解递归:美丽的科赫雪花
- 解决 No resource found that matches the given name (at 'layout_above' with value '@id/button3').
- 基于阈值的全零块判决算法
- 有序数组合并及等长数组对位穿插
- rt thread studio使用QBOOT和片外flash实现OTA升级
- 应用层 - 重学计算机网络系列(2)
- Word恢复文本转换器-修复损坏的WORD文件
- 你是我的四月天[转自天涯]