leetcode27题 题解 翻译 C语言版 Python版
来源:互联网 发布:军用软件接口设计规范 编辑:程序博客网 时间:2024/06/16 11:26
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 in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
Given input array nums = [3,2,2,3]
, val = 3
Your function should return length = 2, with the first two elements of nums being 2.
Hint:
- Try two pointers.
- Did you use the property of "the order of elements can be changed"?
- What happens when the elements to remove are rare?
27.移除元素
给定一个数组和一个值,就地移除所有等于这个值的数组元素并返回新的数组长度。
不要分配内存创建另外的数组,你必须用恒定的内存就地完成。
元素的顺序可以被改变,你不用管在新长度之外数组剩下的元素值。
举例:
给定一个数组nums=[3,2,2,3],val=3
你的函数应该返回length=2,而且nums的前两个元素值应该都为2
提示:
1.尝试用两个指针
2.你用了元素顺序可以改变的特性了吗?
3.当需要移除的元素很少时会发生什么?
思路:由于不需要考虑数组元素相对顺序,所以只需要从前向后遍历,遇到不等于val的元素就将数组尾部的元素移过来覆盖他即可。因为最后超过新数组长度的元素不用管,所以我们可以实时变化新数组长度,这样也能实时表示最后一个可以移过来的元素。需要注意数组只有一个元素并且要移除这个元素时要处理到位,所以第一个指针指向当前元素,第二个指针也即新数组长度表示的应该指向最后一个元素的后面一个位置。
int removeElement(int* nums, int numsSize, int val) { int n = numsSize, i = 0; while(i < n){ if (nums[i] == val){ nums[i] = nums[(n--) - 1]; } else i++; } return n;}
class Solution(object): def removeElement(self, nums, val): """ :type nums: List[int] :type val: int :rtype: int """ n, i = len(nums), 0 while i < n: if nums[i] == val: nums[i] = nums[n - 1] n -= 1 else: i += 1 return n
0 0
- leetcode27题 题解 翻译 C语言版 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版
- leetcode191题 题解 翻译 C语言版 Python版
- leetcode70题 题解 翻译 C语言版 Python版
- leetcode83题 题解 翻译 C语言版 Python版
- leetcode263题 题解 翻译 C语言版 Python版
- leetcode326题 题解 翻译 C语言版 Python版
- Maven的安装配置
- 设置NSBlockOperation依赖
- 【UOJ#149】【NOIP2015】子串【计数DP】
- 生产安装mysql
- 设计模式-备忘录模式(Memento)
- leetcode27题 题解 翻译 C语言版 Python版
- 使用replace()方法往FragmentManager中添加Fragment,频繁切换会崩溃
- 修改NSOperationQueue的最大并发数
- POI之Excel简单导出
- 递归方法求整型数组中最大值
- 延迟执行某个方法
- error: linker command failed with exit code 1 (use -v to see invocation)
- FTP服务器需要开几个端口
- 程序员如何以一敌二