/*
leetCode -- 移动零
*/
public class Remove_zero {
public static void main(String[] args) {
Solution solution = new Solution();
int[] number = new int[]{0,1,0,3,12};
solution.moveZeroes(number);
}
}
上面是测试
//--------------------------------------------------
下面是封装的方法
/**
* 输入: nums = [0,1,0,3,12]
* 输出: [1,3,12,0,0]
* <p>
* 输入: nums = [0]
* 输出: [0]
*/
class Solution {
public void moveZeroes(int[] nums) {
if(nums.length == 0 || nums == null){
return;
}
int[] temp = new int[nums.length];
int t = 0; // < --指针
for (int i = 0; i < nums.length; i++) {
if (nums[i] != 0) {
temp[t] = nums[i];
t++;
}
}
int number = 0;
for (int i : temp) {
if(i == 0){
number++;
}
}
for (int w = 0; w < temp.length - 1 - number; w++) {
for (int i = 0; i > temp.length - 1 - w ; i++) {
if (temp[i] > temp[i + 1]) {
int exchange = temp[i];
temp[i] = temp[i + 1];
temp[i + 1] = exchange;
}
}
}
System.out.println(Arrays.toString(temp));
}
}
解析:
用n和t两个指针,来移动,所谓的”指针”就是定义出来的一个数,在循环中跳动,和++的操作
原创文章,作者:kirin,如若转载,请注明出处:https://blog.ytso.com/275601.html