Topic
Given an array nums
, write a function to move all's to the 0
end of it while maintaining the relative order of the No N-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be[1, 3, 12, 0, 0]
Given an array, write a function that moves all 0 of the array to the end of the array, while maintaining the relative position of all other non-0 elements. Example input:[0,1,0,3,12] output:[1,3,12,0,0]
Code
Method One:
public static void Movezeroes (int[] nums) { int[] nonzeroelements = new Int[nums.length]; int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i]! = 0) { Nonzeroelements[count] = nums[i]; count++; } } for (int i = count; i < nums.length; i++) { Nonzeroelements[count] = 0; count++; } for (int i = 0; i < nums.length; i++) { nums[i] = nonzeroelements[i]; } }
Method Two:
public static void Movezeroes (int[] nums) { int size = 0; for (int i = 0; i < nums.length; i++) { if (Nums[i] > 0) { nums[size] = nums[i]; size++; } } for (int i = size; i < nums.length; i++) { nums[i] = 0; } }
Method Three:
public static void MoveZeroes3 (int[] nums) { int k = 0; for (int i = 0; i < nums.length; i++) { if (Nums[i] > 0) {if (i! = k) { //If there is no 0 in the array, swap swap is not required (nums , I, k++); } else { k++ ; }}} public static void Swap (int[] arr, int i, int j) { int temp = arr[i]; Arr[i] = arr[j]; ARR[J] = temp; }
Array--leetcode283