leetcode 27 题解 翻译 Python版
来源:互联网 发布:mac顶部菜单栏截图工具 编辑:程序博客网 时间:2024/06/07 13:56
27. Remove Element
题目描述:
Given an array and a value, remove all instances of that value in-place 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.
The order of elements can be changed. It doesn’t matter what you leave beyond the new length.
Example 1:
Given nums = [3,2,2,3], val = 3,Your function should return length = 2, with the first two elements of nums being 2.
题目翻译
给定一个数组和一个值,就地删除数组中和该值相同的所有元素并返回新的长度。
不要创建其他数组分配额外的空间,你必须通过O(1)空间复杂度就地修改输入数组来实现这一点。
元素的顺序可以改变。只要返回了新的长度,数组中是否存在超过这个索引的元素无所谓(即数组中高索引元素可以不删除)。
示例1:
给定的数组 = [3,2,2,3], 值 = 3,你的函数应该返回长度=2,数组修改后前两个元素为2
解题方案
标签: Two Pointers
思路:
本题需要维护两个数组指针i和j,从数组0元素遍历至数组最后一个元素。若在数组中发现和给的val值相同的元素,则将数组后面和val值不同的元素前移覆盖这个元素。
算法复杂度O(n)。
代码:
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ i = 0 j = 0 while j < len(nums): if nums[j] == val: # 数组内的值和要删除的元素值相同 j += 1 else: if i != j: # 将数组后边和所给元素不相同的元素前移 nums[i] = nums[j] i += 1 j += 1 del nums[i:len(nums)] # 删除多余元素 return len(nums)
阅读全文
0 0
- leetcode 27 题解 翻译 Python版
- leetcode 19 题解 翻译 Python版
- leetcode 154 题解 翻译 Python版
- LeetCode题解汇总(C++ Java Python,含题目翻译)
- leetcode 题解 翻译 C语言 Python 合集 (不断更新)
- leetcode 部分题解(python)
- leetcode292题 题解 翻译 C语言版 Python版
- leetcode258题 题解 翻译 C语言版 Python版
- leetcode104题 题解 翻译 C语言版 Python版
- leetcode237题 题解 翻译 C语言版 Python版
- leetcode226题 题解 翻译 C语言版 Python版
- leetcode283题 题解 翻译 C语言版 Python版
- leetcode100题 题解 翻译 C语言版 Python版
- leetcode242题 题解 翻译 C语言版 Python版
- leetcode171题 题解 翻译 C语言版 Python版
- leetcode235题 题解 翻译 C语言版 Python版
- leetcode206题 题解 翻译 C语言版 Python版
- leetcode328题 题解 翻译 C语言版 Python版
- orcale对应java关系
- 软件工程(C编码实践篇)学习总结
- windows 10 64bit下安装Tensorflow+Keras+VS2015+CUDA8.0 GPU加速
- R
- 设计模式笔记(二)设计六大原则之二--里氏替换原则
- leetcode 27 题解 翻译 Python版
- 11月6日 哈工大c语言编程题
- ImageNet Classification with Deep Convolutional Networks
- Python 几个字符串常用的方法
- Codeforces Round #350 (Div. 2) B
- bp神经网络
- 11.06笔记整理、作业以及学习心得
- java IO 管道流 PipedInputStream 使这2个线程互相通讯
- xlib一夜学习体会