The title
Given an array nums, write a function to move all zeros to the end of the array.
Example:
Input: [0,1,0,3,12] output: [12,1,3,0,0]Copy the code
Description:
Must operate on the original array, cannot copy additional arrays. Minimize the number of operations.Copy the code
Analysis:
- Double pointer, left pointer at head, right pointer at tail
- When the left pointer is 0, it swaps with the right pointer that is not 0. Then the right pointer moves to the left
- The left pointer moves to the right
- If the right pointer is 0, move to the left
Code:
/ * * *@param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let left = 0, right = nums.length - 1;
if (n <= 1) {
return;
}
while (left < right) {
if (nums[left] == 0 && nums[right]) {
nums[left] = nums[left] ^ nums[right];
nums[right] = nums[left] ^ nums[right];
nums[left] = nums[left] ^ nums[right];
right--;
}
left++;
if (nums[right] == 0) { right--; }}};Copy the code
Deformation problem
Given an array nums, write a function to move all zeros to the end of the array while preserving the relative order of the non-zero elements.
Example:
Input: [0,1,0,3,12] output: [1,3,12,0,0]Copy the code
Description:
Must operate on the original array, cannot copy additional arrays. Minimize the number of operations.Copy the code
Analysis:
- Double Pointers, left and right Pointers in the head
- The fast pointer looks forward for non-zero elements, and the slow pointer looks for zero elements
- When the fast pointer finds a non-zero element, it swaps with the slow pointer
Code:
/ * * *@param {number[]} nums
* @return {void} Do not return anything, modify nums in-place instead.
*/
var moveZeroes = function(nums) {
let left = 0, right = 0, n = nums.length;
if (n <= 1) {
return;
}
while (right < n && left < n) {
if(right ! = left && nums[right] && nums[left] ==0) {
nums[right] = nums[left] ^ nums[right];
nums[left] = nums[left] ^ nums[right];
nums[right] = nums[left] ^ nums[right];
left++;
}
right++;
if(nums[left]) { left++; }}};Copy the code