We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
题目链接: https://leetcode-cn.com/problems/duplicate-zeros
难度: Easy 标签: 数组 双指针
Easy
数组
双指针
The text was updated successfully, but these errors were encountered:
Difficulty: 简单
Related Topics: 数组, 双指针
给你一个长度固定的整数数组 arr,请你将该数组中出现的每个零都复写一遍,并将其余的元素向右平移。
arr
注意:请不要在超过该数组长度的位置写入元素。
要求:请对输入的数组 **就地 **进行上述修改,不要从函数返回任何东西。
示例 1:
输入:[1,0,2,3,0,4,5,0] 输出:null 解释:调用函数后,输入的数组将被修改为:[1,0,0,2,3,0,0,4]
示例 2:
输入:[1,2,3] 输出:null 解释:调用函数后,输入的数组将被修改为:[1,2,3]
提示:
1 <= arr.length <= 10000
0 <= arr[i] <= 9
方法一:利用 splice 的特性
splice
0
i
Language: JavaScript
/** * @param {number[]} arr * @return {void} Do not return anything, modify arr in-place instead. */ var duplicateZeros = function(arr) { for (let i = 0; i < arr.length; i++) { if (!arr[i]) { arr.splice(i, 0, 0); arr.pop(); i++; } } };
方法二: 双指针
countZero
j
/** * @param {number[]} arr * @return {void} Do not return anything, modify arr in-place instead. */ var duplicateZeros = function(arr) { const n = arr.length; let cnt = 0; for (let num of arr) { if (!num) cnt++; } let j = n + cnt; for (let i = n - 1; i >= 0; --i) { if (--j < n) arr[j] = arr[i]; if (!arr[i] && --j < n) arr[j] = 0; } };
Sorry, something went wrong.
No branches or pull requests
题目链接: https://leetcode-cn.com/problems/duplicate-zeros
难度:
Easy
标签:
数组
双指针
The text was updated successfully, but these errors were encountered: