package a4;
import java.util.Arrays;
class Solution {
public static void main(String[] args) {
int[] nums= {0,1,0,3,12};
new Solution().moveZeroes(nums);
}
public void moveZeroes(int[] nums) {
//第一个0与第一个非零数交换
int rightIndex = 0, leftIndex = 0;
//leftIndex代表第一个0的下标
leftIndex = getLeftIndex(nums, leftIndex);
//rightIndex代表第一个非零数的下标
rightIndex = getRightIndex(nums, leftIndex);
while (leftIndex < rightIndex) {
//交换
int temp = nums[leftIndex];
nums[leftIndex] = nums[rightIndex];
nums[rightIndex] = temp;
//往后找满足条件的leftIndex和rightIndex
leftIndex = getLeftIndex(nums, leftIndex);
rightIndex = getRightIndex(nums, leftIndex);
if(nums[leftIndex] == 0 && nums[rightIndex] == 0){
break;
}
}
System.out.println(Arrays.toString(nums));
}
public int getLeftIndex(int[] nums, int leftIndex) {
for (int i = leftIndex; i < nums.length; i++) {
if (nums[i] == 0) {
leftIndex = i;
return leftIndex;
}
}
return 0;
}
public int getRightIndex(int[] nums, int rightIndex) {
for (int i = rightIndex; i < nums.length; i++) {
if (nums[i] != 0) {
rightIndex = i;
return rightIndex;
}
}
return 0;
}
}
283. 移动零
最新推荐文章于 2024-09-11 22:48:33 发布