[算法Rust,Go,Python,JS实现)]LeetCode之27-移除元素
2019-03-23 12:14
826 查看
版权声明:未经博主允许不得转载(https://github.com/ai-word) https://blog.csdn.net/BaiHuaXiu123/article/details/88758739
题目
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。 不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。 元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素。 示例 1: 给定 nums = [3,2,2,3], val = 3, 函数应该返回新的长度 2, 并且 nums 中的前两个元素均为 2。 你不需要考虑数组中超出新长度后面的元素。
思路
采用游标,循环遍历数组,那数组中的值与传进来的值比较,如果不相等,则把游标当前位置的值设置成此时的值。
Rust实现
impl Solution { pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 { if nums.len() == 0 { return 0 } let mut i = 0; for j in 0..nums.len() { if nums[j] != val { nums[i] = nums[j]; i += 1; } } return i as i32; } }
Go语言
func removeElement(nums []int, val int) int { if len(nums) == 0 { return 0 } num := 0 for i:=0;i<len(nums);i++{ if nums[i] != val { nums[num] = nums[i] num ++ } } return num }
JavaScript实现
/** * @param {number[]} nums * @param {number} val * @return {number} */ var removeElement = function(nums, val) { if(nums.length == 0) { return 0 } num = 0 for (let i = 0;i < nums.length;i++) { if (nums[i] !== val) { nums[num] = nums[i] num++ } } return num };
Python实现
class Solution: def removeElement(self, nums: List[int], val: int) -> int: if len(nums) == 0: return 0 num = 0 for i in range(len(nums)): if nums[i] != val: nums[num] = nums[i] num += 1 return num
结果
代码下载地址
相关文章推荐
- [算法Rust,Go,Python,JS实现)]LeetCode之38-报数
- [算法Rust,Go,Python,JS实现)]LeetCode之35-搜索插入位置
- [算法Rust,Go,Python,JS实现)]LeetCode之53-最大子序和
- leetcode的python实现 刷题笔记27:移除元素
- Leetcode 27_移除元素 --python
- LeetCode题解(python)-27. 移除元素
- 【LeetCode】Python实现-203. 移除链表元素
- leetcode 27 移除元素 (python)
- Leetcode做题日记:27. 移除元素(PYTHON)
- 【LeetCode-面试算法经典-Java实现】【082-Remove Duplicates from Sorted List II(排序链表中删除重复元素II)】
- js 动态给元素添加、移除事件的实现方法
- 【LeetCode-面试算法经典-Java实现】【219-Contains Duplicate II(包含重复元素II)】
- Leetcode 27:移除元素(Remove Element)
- LeetCode探索模块初级算法数组章节python3代码实现
- leetcode27. 移除元素
- LeetCode27. 移除元素(Java)
- leetcode 27、移除元素(双指针)
- leetcode 27 Remove Element(移除数组中的与val相等的元素)
- 【算法——Python实现】快速排序的优化:三路快速排序及Leetcode题目应用
- LeetCode - 27. 移除元素