题目链接:largest-number
import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. Note: The result may be very large, so you need to return a string instead of an integer. * */ public class LargestNumber { //解法一 // 221 / 221 test cases passed. // Status: Accepted // Runtime: 250 ms // Submitted: 0 minutes ago //时间复杂度O(n ^ 2) 空间复杂度O(n) public String largestNumber(int[] num) { String largest = ""; List<String> num_str = new ArrayList<String>(); for (int i = 0; i < num.length; i++) { num_str.add(num[i] + ""); } //对数值字符串排序 num_str.sort(new Comparator<String>() { public int compare(String s1, String s2) { String s1Adds2 = s1 + s2; String s2Adds1 = s2 + s1; return s2Adds1.compareTo(s1Adds2); } }); //连接字符 for (int i = 0; i < num_str.size(); i++) { largest += num_str.get(i); } //消除前缀是000...00的情况 int beginIndex = 0; while(beginIndex < largest.length() - 1 && largest.charAt(beginIndex) == '0') beginIndex ++; return largest.substring(beginIndex); } //解法二 // 221 / 221 test cases passed. // Status: Accepted // Runtime: 250 ms // Submitted: 0 minutes ago //时间复杂度O(n ^ 2) 空间复杂度O(n) public String largestNumber1(int[] num) { String largest = ""; List<String> num_str = new ArrayList<String>(); for (int i = 0; i < num.length; i++) { num_str.add(num[i] + ""); } //对数值字符串排序 num_str.sort(new Comparator<String>() { public int compare(String s1, String s2) { int len1 = s1.length(); int len2= s2.length(); if(len1 < len2) { int n = len2 / len1; for (int i = 0; i < n * len1; i += len1) { if (!s2.substring( i, i + len1).equals(s1)) return s2.substring(i, i + len1).compareTo(s1); } if (len2 % len1 != 0) return compare(s1, s2.substring(len2 - len2 % len1, len2)); } else if(len1 > len2){ int n = len1 / len2; for (int i = 0; i < n * len2; i += len2) { if (!s1.substring(i, i + len2).equals(s2)) return s2.compareTo(s1.substring(i, i + len2)); } if (len1 % len2 != 0) return compare(s1.substring(len1 - len1 % len2, len1), s2); } return s2.compareTo(s1); } }); //连接字符 for (int i = 0; i < num_str.size(); i++) { largest += num_str.get(i); } //消除前缀是000...00的情况 int beginIndex = 0; while(beginIndex < largest.length() - 1 && largest.charAt(beginIndex) == '0') beginIndex ++; return largest.substring(beginIndex); } public static void main(String[] args) { } }
原文地址:http://blog.csdn.net/ever223/article/details/44871667