Move Zeroes
Given an integer array nums, move all 0's to the end of it while maintaining the relative order of the non-zero elements.
Note that you must do this in-place without making a copy of the array.
Java
This is the solution I made a few months ago when I was fiddling around leetcode
class Solution {public void moveZeroes(int[] nums){ArrayList<Integer> n = new ArrayList<Integer>();int zeroCount = 0;for(int i = 0; i < nums.length; i++){if(nums[i] != 0)n.add(nums[i]);elsezeroCount++;}for(int i = 0; i < zeroCount; i++)n.add(0);int[] rs = n.stream().mapToInt(i -> i).toArray();for(int i = 0; i < rs.length; i++)nums[i] = rs[i];}}
And this is the solution I've found yesterday.
class Solution {int zeroIndex = 0;for(int currentIndex = 0; currentIndex < nums.length; currentIndex++){if(nums[currentIndex] != 0){int temp = nums[zeroIndex];nums[zeroIndex] = nums[currentIndex];nums[currentIndex] = temp;zeroIndex++;}}}
oddly enough there isn't much difference in speed, first solution took 3ms and 39.2MB of memory while the second solution took 2ms and 54.9 MB of memory.