[LeetCode] 179. Largest Number

The maximum number. Meaning of the questions is to give an array of integers, add them together into a string and returns the largest numeric string. example,

Example 1:

Input: [10,2]
Output: "210"

Example 2:

Input: [3,30,34,5,9]
Output: "9534330"

The idea is a need to write their own comparator function to compare the results of each of the two digital mosaic lexicographic order, for example, requires a relatively large lexicographically in the end it is a large dictionary 210 or 102 sequence. This question is no algorithm to study is whether to achieve their a custom comparator function. JavaScript is not because of the type of data limitations, you can directly compare the size of two numbers.

Time O (nlogn) - sort function

Space O (n)

Java implementation

 1 class Solution {
 2     public String largestNumber(int[] nums) {
 3         // corner case
 4         if (nums == null || nums.length == 0) {
 5             return "";
 6         }
 7 
 8         // normal case
 9         String[] res = new String[nums.length];
10         for (int i = 0; i < nums.length; i++) {
11             res[i] = String.valueOf(nums[i]);
12         }
13         Arrays.sort(res, new Comparator<String>() {
14             @Override
15             public int compare(String str1, String str2) {
16                 String s1 = str1 + str2;
17                 String s2 = str2 + str1;
18                 return s2.compareTo(s1);
19             }
20         });
21         if (res[0].charAt(0) == '0') {
22             return "0";
23         }
24         StringBuilder sb = new StringBuilder();
25         for (String s : res) {
26             sb.append(s);
27         }
28         return sb.toString();
29     }
30 }

 

JavaScript implementation

 1 /**
 2  * @param {number[]} nums
 3  * @return {string}
 4  */
 5 var largestNumber = function (nums) {
 6     // corner case
 7     if (nums.every(n => n === 0)) {
 8         return '0';
 9     }
10 
11     // normal case
12     nums.sort((n1, n2) => {
13         const s1 = new String(n1);
14         const s2 = new String(n2);
15         const first = s1 + s2;
16         const second = s2 + s1;
17         if (first > second) {
18             return -1;
19         } else if (first < second) {
20             return 1;
21         } else return 0;
22     });
23     return nums.join('');
24 };

 

Guess you like

Origin www.cnblogs.com/aaronliu1991/p/12556513.html