LeetCode283 Move Zeroes

    xiaoxiao2023-11-24  125

    题目:

           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.

    public class MoveZero { public static void moveZeroes(int[] nums) { int k = 0;//nums, [0...k)中元素均为非0 //遍历第i个元素后保证nums[0...i]中所有非零元素都按照顺序排列在[0...k]中,同时[k...i]为0 for (int i = 0; i < nums.length; i++) { if (nums[i] != 0) if(i != k) swap(nums, k++, i); else//i==k k++; } } public static void swap(int [] arr, int i , int j){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } public static void main(String[] args) { int[] nums = {0,1,0,3,12}; moveZeroes(nums); System.out.println(Arrays.toString(nums)); } }

          

     

           

    最新回复(0)