Last active
August 29, 2015 14:21
-
-
Save rootid/af38091308e53301883a to your computer and use it in GitHub Desktop.
This file contains hidden or 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
//If the given arrays is {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0} | |
//,it should be changed to {1, 9, 8, 4, 2, 7, 6, 0, 0, 0, 0}. | |
//The order of all other elements should be same. | |
//Expected time complexity is O(n) and extra space is O(1). | |
public static void swap (int a[],int start,int end) { | |
int tmp = a[start]; | |
a[start] = a[end]; | |
a[end] = tmp; | |
} | |
/** | |
* Idea : 1.Count # of Non zero elements | |
* 2.Insert zero after the non zero elements | |
* @param a | |
*/ | |
public static void moveAllZerosToEnd (int a[]) { | |
int end = a.length; | |
int cnt = 0; | |
for (int i=0;i < end;i++) { | |
if (a[i] != 0) { | |
swap(a,i,cnt); | |
cnt++; | |
} | |
} | |
// while (cnt < end) { | |
// a[cnt++] = 0; | |
// } | |
for (int i=0;i<a.length;i++) { | |
System.out.print(a[i] + "," ); | |
} | |
System.out.println(); | |
} | |
public static void main(String[] args) { | |
int a[] = {1, 9, 8, 4, 0, 0, 2, 7, 0, 6, 0}; | |
moveAllZerosToEnd (a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment