179. Largest Number
Problem:
Sort the array first. To determine which number comes first see below.
s1 = "30", s2 = "34"
s1 + s2 = "3034"
s2 + s1 = "3430"
s2 is ahead of s1, so the comparator in lambda expression is (s1, s2) -> (s2 + s1).compareTo(s1 + s2).
Solution:
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:Analysis:[3,30,34,5,9]Output: "9534330"
Sort the array first. To determine which number comes first see below.
s1 = "30", s2 = "34"
s1 + s2 = "3034"
s2 + s1 = "3430"
s2 is ahead of s1, so the comparator in lambda expression is (s1, s2) -> (s2 + s1).compareTo(s1 + s2).
Solution:
class Solution { public String largestNumber(int[] nums) { if (nums == null || nums.length == 0) return ""; String[] strs = new String[nums.length]; for (int i = 0; i < nums.length; i++) { strs[i] = String.valueOf(nums[i]); } Arrays.sort(strs, ((a,b) -> (b + a).compareTo(a + b))); if (strs[0].charAt(0) == '0') return "0"; StringBuilder sb = new StringBuilder(); for (String s: strs) { sb.append(s); } return sb.toString(); } }
评论
发表评论