Last active
August 29, 2015 14:06
-
-
Save dubeme/6ac79fd13000e0568200 to your computer and use it in GitHub Desktop.
Amazon phone interview question
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
/* | |
Start from the end of the array | |
If I come across a non zero, | |
move it to before the last known | |
location of a non zero number | |
*/ | |
void rearrangeArray(int[] nums) | |
{ | |
int lastNonZero = nums.length - 1; | |
boolean foundZero = false; | |
for(int i = nums.length - 1; i>= 0; i--) | |
{ | |
foundZero = foundZero || nums[i] == 0; | |
if(nums[i] != 0) | |
{ | |
if ( foundZero ) | |
{ | |
nums[lastNonZero] = nums[i]; | |
nums[i] = 0; | |
} | |
lastNonZero -= 1; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment