码迷,mamicode.com
首页 > 其他好文 > 详细

【Leetcode】Largest Number

时间:2015-01-16 19:14:01      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:leetcode   java   数学   

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));
	}
}


【Leetcode】Largest Number

标签:leetcode   java   数学   

原文地址:http://blog.csdn.net/qbt4juik/article/details/42779919

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!