leetcode27题 题解 翻译 C语言版 Python版
2016-04-15 09:43
197 查看
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 =
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的元素就将数组尾部的元素移过来覆盖他即可。因为最后超过新数组长度的元素不用管,所以我们可以实时变化新数组长度,这样也能实时表示最后一个可以移过来的元素。需要注意数组只有一个元素并且要移除这个元素时要处理到位,所以第一个指针指向当前元素,第二个指针也即新数组长度表示的应该指向最后一个元素的后面一个位置。
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
相关文章推荐
- 用VS2010编译C++项目时出现这样的错误:
- C++中STL库中的assign函数
- C++实现简单的职工管理系统实训代码
- ANSIC标准定义的C语言预处理指令总结
- [LeetCode]36. Valid Sudoku
- C++:单例模式例题解析
- C++11的tuple用法笔记
- C++STL源代码学习(之slist篇)
- C/C++深度分析
- C++文件读写详解(ofstream,ifstream,fstream)
- 极客班C++ STL(容器)第二周笔记
- C/C++系列之学生管理系统
- C/C++使用模板实现数据栈
- C++空类的大小问题
- C++ vector的用法
- c++进阶之路
- C++多态篇2——虚函数表详解之从内存布局看函数重载,函数覆盖,函数隐藏
- C/C++什么是页抖动?
- C/C++左值&右值
- # 极客班C++OOP(下)第五周笔记