Largest Number Leetcode
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.
这道题就是有些情况不太好想到,而且两个数字比的时候我写的有点复杂了,一开始觉得直接连起来比太耗时,写完了发现好像是一样的。。。= =我的反而要想。。。
注意一下第一个是0的情况。
public class Solution { public String largestNumber(int[] nums) { StringBuilder sb = new StringBuilder(); if (nums == null) { return null; } String[] n = new String[nums.length]; for (int i = 0; i < nums.length; i++) { n[i] = String.valueOf(nums[i]); } Arrays.sort(n, new Comparator<String>(){ public int compare(String a, String b) { int i = 0; int j = 0; int com = 0; while (com < a.length() + b.length()) { char first = i < a.length() ? a.charAt(i) : a.charAt(i % a.length()); char second = j < b.length() ? b.charAt(j) : b.charAt(j % b.length()); i++; j++; com++; if (first == second) { continue; } return second - first; } return 0; } }); if (n[0].equals("0")) { return new String("0"); } for (int i = 0; i < n.length; i++) { sb.append(n[i]); } return sb.toString(); } }
top solution和我的思路一样,不过是连起来比较的。。。简单很多。。。