题目
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.
For example, given nums = [0, 1, 0, 3, 12], after calling your function, nums should be [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.
解析
package ShiyiBa;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Vector;
/**
* Created by xurui on 2017/11/8.
*/
/*
题目:已知数组A,让你把数组nums里非0的数往前移。
基本思路:新建一个数组nonZeroElement,把nums里所有大于0的数按顺序传进去,然后把数组nonZeroElement里的值传给nums,数组nums剩余部分0补齐。
*/
class Solution {
public static void moveZeroes(int[] nums) {
ArrayList<String> nonZeroElement = new ArrayList<String>();
for(int i = 0 ; i < nums.length; i++){
if(nums[i] != 0){
//这里把数组值传给ArraryList
nonZeroElement.add(Integer.toString(nums[i]));
}
}
for(int i = 0 ; i < nonZeroElement.size() ; i++){
//这里把ArraryList传给数组
nums[i] = Integer.parseInt(nonZeroElement.get(i));
}
for(int i = nonZeroElement.size() ; i < nums.length ; i++){
nums[i] = 0;
}
}
}
public class moveZero {
public static void main(String[] args){
int[] arr = {0,1,0,3,12};
Solution a = new Solution();
a.moveZeroes(arr);
for(int i = 0;i < arr.length;i++){
System.out.println(arr[i]);
}
}
}
//一级优化
class Solution {
public void moveZeroes(int[] nums) {
int j = 0;
//非0数移到前面
for(int i = 0 ; i < nums.length; i++ ){
if(nums[i] != 0){
nums[j] = nums[i];
j++;
}
}
//剩余位置为0
for(int i = j;i < nums.length; i++){
nums[i] = 0;
}
}
}
//二级优化
class Solution {
public void moveZeroes(int[] nums) {
int j = 0 , temp = 0 ;//nums中[0...j)的元素均为非0
//遍历到第i个元素时,保证[0...i]中所有非0元素
//都按照顺序排列在[0..k)中
//同时[k..i]为0
for(int i = 0 ; i < nums.length ; i++){
if(nums[i] != 0){
if( i != j){
temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
j++;
}
else //i == k
j++;
}
}
}
}