-
Notifications
You must be signed in to change notification settings - Fork 171
/
LargestNumber.java
64 lines (60 loc) · 2.18 KB
/
LargestNumber.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
Author: King, [email protected]
Date: Jan 13, 2015
Problem: ZigZag Conversion
Difficulty: Medium
Source: https://oj.leetcode.com/problems/largest-number/
Notes:
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330.
Note: The result may be very large, so you need to return a string instead of an integer.
Solution: ...
*/
public class Solution {
public String largestNumber_1(int[] num) {
int size = num.length;
if (size <= 0) return new String();
if (size == 1) return String.valueOf(num[0]);
Comparator<Integer> comp = new Comparator<Integer>(){
public int compare(Integer a, Integer b) {
String aa = ""+a+b;
String bb = ""+b+a;
return bb.compareTo(aa);
}
};
Integer[] in = new Integer[size];
for (int i = 0; i < size; ++i)
in[i] = Integer.valueOf(num[i]);
Arrays.sort(in, comp);
StringBuffer res = new StringBuffer();
int i = 0;
while ((i < in.length - 1) && (in[i] == 0)) ++i;
while (i < in.length) res.append(in[i++]);
return res.toString();
}
public String largestNumber_2(int[] num) {
int size = num.length;
if (size <= 0) return new String();
String[] in = new String[size];
for (int i = 0; i < size; ++i)
in[i] = String.valueOf(num[i]);
return foo(in);
}
public String foo(String[] in) {
if (in.length == 0) return new String();
if (in.length == 1) return in[0];
StringBuffer res = new StringBuffer();
Comparator<String> comp = new Comparator<String>(){
public int compare(String a, String b) {
String aa = a+b;
String bb = b+a;
return bb.compareTo(aa);
}
};
Arrays.sort(in, comp);
int i = 0;
while ((i < in.length - 1) && (in[i].compareTo("0") == 0)) ++i;
while (i < in.length) res.append(in[i++]);
return res.toString();
}
}