welcome to my blog
LeetCode Top 100 Liked Questions 283. Move Zeroes (Java版; Easy)
题目描述
Given an array nums, write a function to move all 0's to the end of it while maintaining the relative
order of the non-zero elements.
Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.
第二次做; 双指针, 核心: 1) i指向当前元素, j指向非零元素的下一个位置, j初始值为0; 2)当前元素为0时不处理; 当前元素非零时, 将当前元素放在j位置, 然后j++;
/*
特殊的双指针, i指向当前元素, j指向最后一个不为0的元素的下一个位置
当前元素为0时, 不处理
当前元素不为0时, 将当前元素赋给j位置
*/
class Solution {
public void moveZeroes(int[] nums) {
int n = nums.length;
int j=0;
for(int i=0; i<n; i++){
if(nums[i]!=0){
nums[j] = nums[i];
j++;
}
}
for(; j<n; j++)
nums[j] = 0;
}
}
第一次做; 双指针法, 把非零元素挪到数组前面, 剩下的位置置零; 具体地, 遍历数组元素, 如果当前元素等于0, 不处理; 如果当前元素不等于0,将当前元素挪到前面去nums[i]=nums[j]; i++;
遍历结束后将剩余位置置零
执行用时 :0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗 :37.5 MB, 在所有 Java 提交中击败了95.54%的用户
/*
双指针解法:将非零元素挪到数组前面, 然后剩下的位置置零
时间复杂度O(N)
*/
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null || nums.length==0)
return;
int i=0;
for(int j=0; j<nums.length; j++){
if(nums[j]!=0){
nums[i]=nums[j];
i++;
}
}
for(; i<nums.length; i++)
nums[i] = 0;
}
}
第一次做; 插入排序思想; 因为插入排序是稳定的, 所以使用插入排序的思路不会影响元素之间的相对顺序; 根据当前元素是否是0分成两大类情况进行讨论: 1)当前元素是0, 不处理; 2)当前元素不是0, 将当前元素挪到0元素前面或者挪到数组的第一个位置; 但是这个方法的速度很慢, 因为时间复杂度是O(N^2)
执行用时 :24 ms, 在所有 Java 提交中击败了20.31%的用户
内存消耗 :37.7 MB, 在所有 Java 提交中击败了95.42%的用户
/*
插入排序思想
*/
class Solution {
public void moveZeroes(int[] nums) {
if(nums==null || nums.length==0)
return;
for(int i=1; i<nums.length; i++){
if(nums[i]==0)
continue;
for(int j=i; j>=1 && nums[j-1]==0; j--){
swap(nums,j, j-1);
}
}
}
public void swap(int[] arr, int i, int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
复习一下排序算法的稳定性