Given a list of non-negative integers, arrange them such that they form the largest number.
Example 1:
Input: [10, 2]
Output: 210
Example 2:
Input: [3,30,34,5,9]
Output: 9534330
Solution:
1: class Solution {
2: public String largestNumber(int[] nums) {
3: if(nums == null || nums.length == 0)
4: return "";
5:
6: String[] s_num = new String[nums.length];
7: for(int i = 0; i< nums.length; i++){
8: s_num[i] = String.valueOf(nums[i]);
9: }
10:
11: Comparator<String> comp = new Comparator<String>(){
12: @Override()
13: public int compare(String s1, String s2){
14: String str1 = s1+s2;
15: String str2 = s2+s1;
16: return str2.compareTo(str1);
17: }
18: };
19:
20: Arrays.sort(s_num, comp);
21: if(s_num[0].charAt(0) == '0')
22: return "0";
23:
24: StringBuffer sb = new StringBuffer();
25: for(String s: s_num){
26: sb.append(s);
27: }
28:
29: return sb.toString();
30: }
31: }
Let's assume:
the length of input array is n,
The average length of Strings in s_num is k,
Comparing two strings will take O(k).
Sorting will take O(nlogn)
Appending to StringBuilder takes O(n).
So total will be O(nklognk) + O(n) = O(nklognk).
the length of input array is n,
The average length of Strings in s_num is k,
Comparing two strings will take O(k).
Sorting will take O(nlogn)
Appending to StringBuilder takes O(n).
So total will be O(nklognk) + O(n) = O(nklognk).
Space complexity: O(n).
No comments:
Post a Comment