Created
April 12, 2020 18:22
-
-
Save ozkansari/ac4265bf3c4e19c843b9482a9ffe11f0 to your computer and use it in GitHub Desktop.
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. https://leetcode.com/explore/challenge/card/30-day-leetcoding-challenge/528/week-1/3286/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
import java.util.stream.Collectors; | |
public class MoveZeroes { | |
public static void main(String[] args) { | |
MoveZeroes problem = new MoveZeroes(); | |
int[] result1 = problem.calculate(new int[] { 0, 1, 0, 3, 12 }); | |
System.out.println( | |
"Expected: [1,3,12,0,0], " + "Result: " + Arrays.stream(result1).boxed().collect(Collectors.toList())); | |
} | |
/** | |
* 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. | |
* | |
* @param nums | |
* @return | |
*/ | |
public int[] calculate(final int[] nums) { | |
int[] result = Arrays.copyOf(nums, nums.length); | |
int countZero = 0; | |
boolean moveNums = false; | |
for (int i = 0; i < result.length; i++) { | |
if (result[i] == 0) { | |
countZero++; | |
moveNums = true; | |
} else if (moveNums) { | |
result[i - countZero] = result[i]; | |
} | |
} | |
while (countZero > 0) { | |
result[result.length - countZero] = 0; | |
countZero--; | |
} | |
return result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment