Welcome to Subscribe On Youtube
Question
Formatted question description: https://leetcode.ca/all/179.html
Given a list of non-negative integers nums
, arrange them such that they form the largest number and return it.
Since the result may be very large, so you need to return a string instead of an integer.
Example 1:
Input: nums = [10,2] Output: "210"
Example 2:
Input: nums = [3,30,34,5,9] Output: "9534330"
Constraints:
1 <= nums.length <= 100
0 <= nums[i] <= 109
Algorithm
For two numbers a and b, if you convert them to strings, if ab> ba, then a will be ranked first,
- For example, 9 and 34, since 934>349, 9 is in front,
- For example, 30 and 3, because 303<330, 3 is in front of 30.
After sorting the original array according to this rule, converting each number into a string and then concatenating it is the final result.
Code
-
import java.util.Arrays; import java.util.Comparator; public class Largest_Number { class Solution { public String largestNumber(int[] nums) { // Get input integers as strings. String[] asStrs = new String[nums.length]; for (int i = 0; i < nums.length; i++) { asStrs[i] = String.valueOf(nums[i]); } // Sort strings according to custom comparator. Arrays.sort(asStrs, new LargerNumberComparator()); // If, after being sorted, the largest number is `0`, the entire number // is zero. if (asStrs[0].equals("0")) { return "0"; } // Build largest number from sorted array. String largestNumberStr = new String(); for (String numAsStr : asStrs) { largestNumberStr += numAsStr; } return largestNumberStr; } private class LargerNumberComparator implements Comparator<String> { @Override public int compare(String a, String b) { String order1 = a + b; String order2 = b + a; return order2.compareTo(order1); } } } } ############ class Solution { public String largestNumber(int[] nums) { List<String> vs = new ArrayList<>(); for (int v : nums) { vs.add(v + ""); } vs.sort((a, b) -> (b + a).compareTo(a + b)); if ("0".equals(vs.get(0))) { return "0"; } return String.join("", vs); } }
-
// OJ: https://leetcode.com/problems/largest-number/ // Time: O(NlogN * W) where W is the max length of the number strings. // Space: O(NW) class Solution { public: string largestNumber(vector<int>& A) { vector<string> v; for (int n : A) v.push_back(to_string(n)); sort(begin(v), end(v), [](auto &a, auto &b) { for (int i = 0; i < a.size() + b.size(); ++i) { char x = i < a.size() ? a[i] : b[i - a.size()], y = i < b.size() ? b[i] : a[i - b.size()]; if (x != y) return x > y; } return false; // don't return true which will result in infinite loop }); if (v[0] == "0") return "0"; string ans; for (auto &s : v) ans += s; return ans; } };
-
class Solution: def largestNumber(self, nums: List[int]) -> str: nums = [str(v) for v in nums] nums.sort(key=cmp_to_key(lambda a, b: 1 if a + b < b + a else -1)) return "0" if nums[0] == "0" else "".join(nums) ############ class Solution: # @param {integer[]} nums # @return {string} def largestNumber(self, nums): def cmpFunc(a, b): stra, strb = str(a), str(b) if stra + strb < strb + stra: return -1 elif stra + strb > strb + stra: return 1 else: return 0 nums.sort(cmp=cmpFunc, reverse=True) return "".join(str(num) for num in nums) if sum(nums) != 0 else "0"
-
func largestNumber(nums []int) string { vs := make([]string, len(nums)) for i, v := range nums { vs[i] = strconv.Itoa(v) } sort.Slice(vs, func(i, j int) bool { return vs[i]+vs[j] > vs[j]+vs[i] }) if vs[0] == "0" { return "0" } return strings.Join(vs, "") }
-
using System; using System.Globalization; using System.Collections.Generic; using System.Linq; using System.Text; public class Comparer: IComparer<string> { public int Compare(string left, string right) { return Compare(left, right, 0, 0); } private int Compare(string left, string right, int lBegin, int rBegin) { var len = Math.Min(left.Length - lBegin, right.Length - rBegin); for (var i = 0; i < len; ++i) { if (left[lBegin + i] != right[rBegin + i]) { return left[lBegin + i] < right[rBegin + i] ? -1 : 1; } } if (left.Length - lBegin == right.Length - rBegin) { return 0; } if (left.Length - lBegin > right.Length - rBegin) { return Compare(left, right, lBegin + len, rBegin); } else { return Compare(left, right, lBegin, rBegin + len); } } } public class Solution { public string LargestNumber(int[] nums) { var sb = new StringBuilder(); var strs = nums.Select(n => n.ToString(CultureInfo.InvariantCulture)).OrderByDescending(s => s, new Comparer()); var nonZeroOccurred = false; foreach (var str in strs) { if (!nonZeroOccurred && str == "0") continue; sb.Append(str); nonZeroOccurred = true; } return sb.Length == 0 ? "0" : sb.ToString(); } }