Title Description
283. Mobile Zero
Given the nums an array, a write function to all moved to the end of the array 0, while maintaining the relative order of nonzero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Description:Must be operated on the original array, you can not copy additional array.
Minimize the number of operations.Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/move-zeroes
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
answer:
Solution 1:
Personal thoughts:
The head from the tail, sequentially judge whether the element of 0, if it is, and also the right element is not 0, the switching element and the element position to the right, to the position I after the exchange.
164 ms
/** * @param {number[]} nums * @return {void} Do not return anything, modify nums in-place instead. */ var moveZeroes = function(nums) { for(let i = nums.length; i>=0; i--){ if (nums[i]===0 && nums[i+1] && nums[i+1]!==0){ [nums[i],nums[i+1]] = [nums[i+1],nums[i]] i+=2 } } };
Solution 2:
Already the fastest answer: 56 ms
Two pointers, a start point 0, a point to end length-1;
Cycle, the start time is less than the end, this element if the start index is 0, then the deleted element, push the tail into a 0, the left end (end--);
If the start of the index element is not 0, start ++, continues to judge ......
const moveZeroes = nums => { const max = nums.length let start = 0 let end = max - 1 while (start < end) { const item = nums[start] if (item === 0) { nums.splice(start, 1) nums.push(0) end-- continue } start++ } return nums }
A3:
Use a for loop to achieve similar ideas to answer 2. 96ms
Ps: My first answer, the conditions for cycling in using i <nums.length, this will lead to multi-cycle behind a good number of useless 0, resulting in a timeout, the introduction of dynamic end to resolve this issue.
var moveZeroes = function(nums) { let end = nums.length for(let i = 0; i<end; i++){ if(nums[i]===0){ nums.splice(i,1) nums.push(0) i-- end-- } } };