179. Largest Number
Largest Number https://leetcode.com/problems/largest-number/discuss/53158/My-Java-Solution-to-share https://www.javatpoint.com/java-string-compareto https://en.wikipedia.org/wiki/Lexicographical_order https://leetcode.com/problems/largest-number/discuss/53158/My-Java-Solution-to-share For example, using the natural order of the integers, the lexicographical ordering on the subsets of three elements of S = {1, 2, 3, 4, 5, 6} is 123 < 124 < 125 < 126 < 134 < 135 < 136 < 145 < 146 < 156 < 234 < 235 < 236 < 245 < 246 < 256 < 345 < 346 < 356 < 456. The idea here is basically implement a String comparator to decide which String should come first during concatenation. Because when you have 2 numbers (let's convert them into String), you'll face only 2 cases: For example: String s1 = "9"; String s2 = "31"; String case1 = s1 + s2; // 931 String case2 = s2 + s1; // 319 Apparently, case1 is greater than case2 in terms of value. So, we should always put s1 in front of s2. class Solution { public String largestNumber(int[] num) { if(num == null ||num.length == 0){ return ""; } // convert int array to string array, so we can concatenate. otherwise, if we still use int, combine two int, would
// say combine 57, 26, its gonna be 56 * 100 + 26 ,
String[] strArray = new String[num.length]; for(int i = 0; i < num.length; i++){ strArray[i] = String.valueOf(num[i]); // String.valueOf } // comparator fo decide which string should come first in concatenation Arrays.sort(strArray, new Comparator<String>(){ @Override public int compare (String str1, String str2){ String s1 = str1 + str2; String s2 = str2 + str1; return s2.compareTo(s1); // reverse order } }); // an extrmem case when you have bunch of 0s in the int array if(strArray[0].charAt(0) == '0'){ return "0"; } StringBuilder sb = new StringBuilder(); for(String s : strArray){ sb.append(s); } return sb.toString(); } }
class Solution { public String largestNumber(int[] nums) { ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < nums.length; i++) list.add(Integer.toString(nums[i])); Collections.sort(list,(a,b) -> (int)(Long.parseLong(b+a) - Long.parseLong(a+b)) ); StringBuilder sb = new StringBuilder(); for(String x:list) { sb.append(x); } //remove leading 0 return sb.toString().replaceFirst("^0+(?!$)", ""); } }
class Solution { public String largestNumber(int[] nums) { ArrayList<String> list = new ArrayList<>(); for (int i = 0; i < nums.length; i++) list.add(Integer.toString(nums[i])); Collections.sort(list,(a,b) -> Integer.valueOf(b+a) - Integer.valueOf(a+b)); StringBuilder sb = new StringBuilder(); for(String x:list) { sb.append(x); } //remove leading 0 return sb.toString().replaceFirst("^0+(?!$)", ""); } }
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"
posted on 2018-08-28 20:13 猪猪🐷 阅读(102) 评论(0) 收藏 举报
浙公网安备 33010602011771号