LeetCode 27 | Remove Element 删除数组元素
题目描述
Given an array nums and a value val, 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:
nums = [3,2,2,3]
val = 3,
return length = 2, with the first two elements of nums being 2.
就是原地删除值为val的数组元素,空间复杂度限定为O(1),不允许开辟新数组
分析
简单题, 使用双指针,初始化两个指针i 和 j 在数组头部, 并且 j 比 i 移动的快。
如果 j 指针指向的元素不等于 val, 那么就用 j 指针位置的值复制到 i 指针上, 将 i 指针和 j 指针同时移动到下一位。
如果 j 等于 val, j 指针向右移动一位跳过当前元素
Javascript
/**
* @param {number[]} nums
* @param {number} val
* @return {number}
*/
var removeElement = function(nums, val) {
let i = 0
for (let j = 0; j < nums.length; j++) {
// nums[j]为所给值, 什么都不做,j 向右跳一位
if (nums[j] === val) {
continue
}
// nums[j]不等于val时,把mums[j]复制到nums[i], i 和 j 同时向右走一位
nums[i++] = nums[j]
}
return i
};
运行结果
Leave LeetCode 27 | Remove Element 删除数组元素 to:
Read more #esteem posts
Best Posts From Hughie8
We have not curated any of hughie8's posts yet. But you can encourage our curation team to review posts by visiting them regularly and by referring other readers. Because we give priority to frequently read content.
More Posts From Hughie8
- 初次使用SteemPlus, 这款插件挺好用的
- 杭州某互联网公司给程序员发的年中福利,,植发治疗服务,,
- LeetCode 27 | Remove Element 删除数组元素
- LeetCode 5 | Longest Palindromic Substring 最长回文子串
- LeetCode 4 | Median of Two Sorted Arrays 寻找两个有序数组的中位数
- mini 5降价了 购一台
- LeetCode 3 | Longest Substring Without Repeating Characters 无重复字符的最长子串
- 大份吃不起,小份不够吃,,
- LeetCode 2 | Add Two Numbers 两数相加
- LeetCode 1 | Two Sum 两数之和