LeetCode: Largest Number 解题报告 以及Comparator, CompareTo 应用
Largest Number
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.
Credits:
Special thanks to @ts for adding this problem and creating all test cases.
SOLUTION 1:
参考http://bookshadow.com/weblog/2015/01/13/leetcode-largest-number/的解法:
贪心思路:对于两个备选数字a和b,如果str(a) + str(b) > str(b) + str(a),则a在b之前,否则b在a之前
按照此原则对原数组从大到小排序即可
时间复杂度O(nlogn)
易错样例:
Input: [0,0]
Output: "00"
Expected: "0"
JAVA CODE:
public class Solution {
public String largestNumber(int[] num) {
// 1045
// 1111 begin.
if (num == null) {
return null;
} ArrayList<Integer> list = new ArrayList<Integer>();
for (int n1: num) {
list.add(n1);
} Collections.sort(list, new Comparator<Integer>(){
public int compare(Integer o1, Integer o2) {
String s1 = "" + o1 + o2;
String s2 = "" + o2 + o1; return s2.compareTo(s1);
}
}); StringBuilder sb = new StringBuilder();
for (int n: list) {
sb.append(n);
} if (sb.charAt() == '') {
return "";
} return sb.toString();
}
}
附上一些关于Comparator ,comparable 的解释:
Comparator 是一个独立的比较器,里面implements "compare",而Comparable 可以由class本身来implement。
http://stackoverflow.com/questions/4108604/java-comparable-vs-comparator
Java : Comparable vs Comparator [duplicate]
When your class implements Comparable, the compareTo method of the class is defining the "natural" ordering of that object. That method is contractually obligated (though not demanded) to be in line with other methods on that object, such as a 0 should always be returned for objects when the .equals() comparisons return true.
A Comparator is its own definition of how to compare two objects, and can be used to compare objects in a way that might not align with the natural ordering.
For example, Strings are generally compared alphabetically. Thus the "a".compareTo("b") would use alphabetical comparisons. If you wanted to compare Strings on length, you would need to write a custom comparator.
In short, there isn't much difference. They are both ends to similar means. In general implement comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.
相关reference:
http://examples.javacodegeeks.com/core-java/util/comparator/java-comparator-example/
CompareTo示例:
以下的小例子展示了CompareTo的用法:
Card 这个class 使用compareTo函数来实现内建的排序规则,输出如下:
false
1
2
4
public static void main(String[] strs) {
int[] num = {, };
largestNumber(num); ArrayList<Card> cards = new ArrayList<Card>();
Card card1 = new Card();
Card card2 = new Card();
Card card3 = new Card(); cards.add(card1);
cards.add(card2);
cards.add(card3); if (card1.compareTo(card2) > ) {
System.out.println("true");
} else {
System.out.println("false");
} // uses compareTo method implemented in Card object to compare them
Collections.sort(cards); // uses compare method implements in Comparator class
//Collections.sort(cards, new CompareBySuitRank()); for (Card card : cards)
System.out.println(card.toString()); } public static class Card implements Comparable<Card>{
int val; public String toString() {
return "" + val;
} public Card(int val) {
super();
this.val = val;
} public int compareTo(Card o) {
return this.val - o.val;
}
}
Github:
https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/string/LargestNumber.java
LeetCode: Largest Number 解题报告 以及Comparator, CompareTo 应用的更多相关文章
- 【LeetCode】Largest Number 解题报告
[LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...
- 【LeetCode #179】Largest Number 解题报告
原题链接:Largest Number 题目描述: Given a list of non negative integers, arrange them such that they form th ...
- 【原创】leetCodeOj --- Largest Number 解题报告
原题地址: https://oj.leetcode.com/problems/largest-number/ 题目内容: Given a list of non negative integers, ...
- LeetCode: Valid Number 解题报告
Valid NumberValidate if a given string is numeric. Some examples:"0" => true" 0.1 ...
- 【LeetCode】306. Additive Number 解题报告(Python)
[LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...
- LeetCode: Combination Sum 解题报告
Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...
- 【九度OJ】题目1040:Prime Number 解题报告
[九度OJ]题目1040:Prime Number 解题报告 标签(空格分隔): 九度OJ 原题地址:http://ac.jobdu.com/problem.php?pid=1040 题目描述: Ou ...
- [LeetCode] 179. Largest Number 解题思路
Given a list of non negative integers, arrange them such that they form the largest number. For exam ...
- [LeetCode] Largest Number 最大组合数
Given a list of non negative integers, arrange them such that they form the largest number. For exam ...
随机推荐
- MySQL 5.7.14 net start mysql 服务无法启动
解决方法: 1.mysqld --initialize 初始化data目录 2.重新输入net start mysql命令 补充,服务停止的方法:net stop mysql
- Flutter常用组件(Widget)解析-Text
单一格式的文本. 文本组件是以字符串形式显示的单一格式,这个文本字符串可以是多行显示也可以是单独一行显示,主要取决于你的布局限制. 这样式内容是可选择的,如果你省略了,则会使用文本的默认样式来显示.如 ...
- go语言学习-安装和配置
go的安装方式主要有两种,一种直接使用系统自带的软件源来安装,比如 ubuntu 可以直接使用 apt 安装,但通常这种方式安装的都不会是最新的.所以通常直接下载最新的安装包,可以到GoCN下载.下面 ...
- 洛谷.3254.圆桌问题(最大流ISAP)
题目链接 日常水题 还是忍不住吐槽这题奇怪的评价 #include <cstdio> #include <cctype> #include <algorithm> ...
- BZOJ.4241.历史研究(回滚莫队 分块)
题目链接 \(Description\) 长度为n的数列,m次询问,每次询问一段区间最大的 \(A_i*tm_i\) (重要度*出现次数) \(Solution\) 好像可以用莫队做,但是取max的操 ...
- 探究functools模块wraps装饰器的用途
<A Byte of Python>17.8节讲decorator的时候,用到了functools模块中的一个装饰器:wraps.因为之前没有接触过这个装饰器,所以特地研究了一下. 何谓“ ...
- [USACO11FEB]Generic Cow Protests
思路: 动态规划.首先处理出这些数的前缀和$a$,$f_i$记录从第$1$位到第$i$位的最大分组数量.DP方程为:$f_i=max(f_i,f_j+1)$,其中$j$满足$a_i-a_j≥0$. # ...
- netty相关
https://my.oschina.net/jamaly/blog/272385两个客户端之间的交互 http://blog.csdn.net/a953713428/article/details/ ...
- 随机查出满足条件的5条数据(tp5)
随机查出满足条件的5条数据 public function showQuestion() { $data[; $data[ $data['level'] = (int)$data['level']; ...
- C# 添加动态属性
1.ExpandoObject(System.Dynamic) 2.JObject(Newtonsoft.Json.Linq)