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.

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 应用的更多相关文章

  1. 【LeetCode】Largest Number 解题报告

    [LeetCode]Largest Number 解题报告 标签(空格分隔): LeetCode 题目地址:https://leetcode.com/problems/largest-number/# ...

  2. 【LeetCode #179】Largest Number 解题报告

    原题链接:Largest Number 题目描述: Given a list of non negative integers, arrange them such that they form th ...

  3. 【原创】leetCodeOj --- Largest Number 解题报告

    原题地址: https://oj.leetcode.com/problems/largest-number/ 题目内容: Given a list of non negative integers, ...

  4. LeetCode: Valid Number 解题报告

    Valid NumberValidate if a given string is numeric. Some examples:"0" => true" 0.1 ...

  5. 【LeetCode】306. Additive Number 解题报告(Python)

    [LeetCode]306. Additive Number 解题报告(Python) 标签(空格分隔): LeetCode 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http: ...

  6. LeetCode: Combination Sum 解题报告

    Combination Sum Combination Sum Total Accepted: 25850 Total Submissions: 96391 My Submissions Questi ...

  7. 【九度OJ】题目1040:Prime Number 解题报告

    [九度OJ]题目1040:Prime Number 解题报告 标签(空格分隔): 九度OJ 原题地址:http://ac.jobdu.com/problem.php?pid=1040 题目描述: Ou ...

  8. [LeetCode] 179. Largest Number 解题思路

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

  9. [LeetCode] Largest Number 最大组合数

    Given a list of non negative integers, arrange them such that they form the largest number. For exam ...

随机推荐

  1. POJ 2318 TOYS (叉乘判断)

    <题目链接> 题目大意: 给出矩形4个点和n个挡板俩顶点的位置,这n个挡板将该矩形分成 n+1块区域,再给你m个点的坐标,然你输出每个区域内有几个点. 解题思路: 用叉乘即可简单判断点与直 ...

  2. 洛谷 P1464 Function【记忆化搜索】

    题目链接 题目描述 对于一个递归函数w(a,b,c) 如果a<=0 or b<=0 or c<=0就返回值1. 如果a>20 or b>20 or c>20就返回w ...

  3. BZOJ.1927.[SDOI2010]星际竞速(无源汇上下界费用流SPFA /最小路径覆盖)

    题目链接 上下界费用流: /* 每个点i恰好(最少+最多)经过一次->拆点(最多)+限制流量下界(i,i',[1,1],0)(最少) 然后无源汇可行流 不需要源汇. 注: SS只会连i',求SS ...

  4. Linux学习笔记13—Vi编辑器的学习

    文本编辑工具vim.vi1. vim与vi的最大区别是vim编辑的时候是带颜色显示的.Vi不带颜色显示.2. yum install -y vim-enhanced 如果没有安装VIM 使用上面的命令 ...

  5. C++ operator重载运算符和隐式转换功能的实现

    C++ operator重载运算符和隐式转换功能的实现: #include <iostream> using namespace std; class OperatorTest { pub ...

  6. IAAS、SAAS 和 PAAS 的区别、理解

    通俗的讲: 如果你是一个网站站长,想要建立一个网站.不采用云服务,你所需要的投入大概是:买服务器,安装服务器软件,编写网站程序.现在你追随潮流,采用流行的云计算,如果你采用IaaS服务,那么意味着你就 ...

  7. AngularJS中页面呈现html代码段

    如何在页面呈现一段html代码段呢? 在textarea中我们这样写: <textarea name="" id="" cols="30&quo ...

  8. 详解SpringMVC中Controller的方法中参数的工作原理

    Spring MVC中Controller的处理方法的参数可以是Integer,String,自定义对象,ServletRequest,ServletResponse,ModelAndView等等,非 ...

  9. WIN10平板如何打开文件夹选项

    打开计算机,然后查看,最后可以找到选项  

  10. Django中使用Celery,定制应用程序中定义的shared_task未在定期任务管理页面的注册任务中显示

    解决办法: 在项目 proj/proj/celery.py文件中,看到下面这行配置: celery_app.config_from_object('django.conf:settings', nam ...