Last active
December 19, 2015 11:19
-
-
Save vaskoz/5946735 to your computer and use it in GitHub Desktop.
Swap any num[i] and num[j] such that you return the smallest number possible.
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
import java.util.Arrays; | |
public class OneSwapMinNumber { | |
/** | |
* Worst case running time | |
* O(11*k) - k is the number of digits in the number (length of string) | |
*/ | |
public static String min(String num) { | |
char[] digits = num.toCharArray(); | |
int[] rindex = new int[10]; | |
Arrays.fill(rindex, -1); | |
for (int i = 0; i < digits.length; i++) { | |
rindex[digits[i]-'0'] = i; | |
} | |
boolean finished = false; | |
for (int i = 0; i < digits.length; i++) { | |
if (finished) break; | |
int found = digits[i] - '0'; | |
for (int j = (i==0)?1:0; j < found; j++) { | |
if (rindex[j] > i) { | |
char temp = digits[i]; | |
digits[i] = digits[rindex[j]]; | |
digits[rindex[j]] = temp; | |
finished = true; | |
break; | |
} | |
} | |
} | |
return new String(digits); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment