LeetCode 179. Largest Number(最大数)
2016-05-25 01:36
471 查看
原题网址:https://leetcode.com/problems/largest-number/
Given a list of non negative integers, arrange them such that they form the largest number.
For example, given
Note: The result may be very large, so you need to return a string instead of an integer.
方法:将数字按照字符串进行比较,当两个数字为包含关系的时候(例如数字80和806,则将它们连接起来比较,80806和80680,看谁大,谁就应该排在前面)。
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.
方法:将数字按照字符串进行比较,当两个数字为包含关系的时候(例如数字80和806,则将它们连接起来比较,80806和80680,看谁大,谁就应该排在前面)。
public class Solution { public String largestNumber(int[] nums) { String[] strs = new String[nums.length]; for(int i=0; i<nums.length; i++) strs[i] = Integer.toString(nums[i]); Arrays.sort(strs, new Comparator<String>() { @Override public int compare(String s1, String s2) { if (s1.length() == s2.length()) return s2.compareTo(s1); return (s2+s1).compareTo(s1+s2); } }); if ("0".equals(strs[0])) return "0"; StringBuilder sb = new StringBuilder(); for(int i=0; i<strs.length; i++) { sb.append(strs[i]); } return sb.toString(); } }
相关文章推荐
- LeetCode 173. Binary Search Tree Iterator(二叉搜索树迭代器)
- LeetCode 172. Factorial Trailing Zeroes(0结尾)
- LeetCode 171. Excel Sheet Column Number(Excel列号)
- LeetCode 170. Two Sum III - Data structure design(两数和)
- 完全移除TFS2013的版本控制
- Rest API 设计最佳实践(1)
- LeetCode 350. Intersection of Two Arrays II(数组交集)
- LeetCode 174. Dungeon Game(游戏)
- LeetCode 187. Repeated DNA Sequences(重复DNA序列)
- LeetCode 351. Android Unlock Patterns(安卓解锁)
- C#匹配中文字符串的4种正则表达式分享
- Redis中基本数据类型的操作
- Android 简单的条形颜色选择器
- 独立看门狗
- 匹配中文字符的正则表达式: [/u4e00-/u9fa5]
- xml解析之SAX
- Restful接口设计
- 思
- JavaWeb会话管理:(2)Session
- This Handler class should be static or leaks may occur (anonymous android.os.Handler)