【Leetcode】Largest Number

来源:互联网 发布:淘宝海外直购靠谱吗 编辑:程序博客网 时间:2024/06/11 18:08

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.

这道题还是有一定难度的,关键在于你要对数字怎么排序,后来我想到一个好办法:

比如85和859谁放在前面后呢?

让85859和85985比一下,也就是说

compare(int a,int b){

return Long.parseLong(a+""+b)- Long.parseLong(a+""+b);

}

所以其他的就简单啦~

package testAndfun;import java.util.Arrays;import java.util.Comparator;public class largestNumber {public static void main(String[] args) {largestNumber ln = new largestNumber();int[] in = { 3, 2, 54, 9, 85, 859, 99 };//sortNum(in);System.out.println(ln.biggestNumber(in));}// 按自定义规则排序public static void sortNum(int[] a) {int temp = 0;for (int i = a.length - 1; i > 0; --i) {for (int j = 0; j < i; ++j) {if (compare(a[j+1],a[j])<0) {temp = a[j];a[j] = a[j + 1];a[j + 1] = temp;}}}}// 输出public String biggestNumber(int[] num) {String output = new String();sortNum(num);for (int i = num.length-1; i >= 0; i--) {output += num[i] + "";}if(output.length()>1 && output.charAt(0)=='0')return 0+"";return output;}// 排序规则public static int compare(int o1, int o2) {String s1 = o1 + "" + o2;String s2 = o2 + "" + o1;return (int) (Long.parseLong(s1) - Long.parseLong(s2));}}


0 0
原创粉丝点击