Chinaunix首页 | 论坛 | 博客
  • 博客访问: 986323
  • 博文数量: 150
  • 博客积分: 3017
  • 博客等级: 少校
  • 技术积分: 3829
  • 用 户 组: 普通用户
  • 注册时间: 2011-11-19 14:40
个人简介

Now in Baidu WISE team

文章分类

全部博文(150)

文章存档

2014年(8)

2013年(31)

2012年(111)

分类: Java

2014-02-26 16:21:13

给定几个数字,要求构造出一个值最大的数。
例如 8, 99, 10, 3200 ,拼接出的最大数是998320010。

思路:
贪心。
考虑拼接出的数,显然如果一个数第一位是9 那么应该放在最左边。
剩下的数,同样的道理,选出第一位最大的那个值,往后拼接。如果他们的第一位相等,则比较第二位,若还是相等,再比较下一位,还是取大的数拼接到后面。
如果两个数,位数不同,且短的和长的前几位完全相同,例如9911和,99, 头两位都相等,那么我们选择短的那个,因为991199和999911相比,还是后者要更大。

根据这个原则,我们可以对输入数组进行“排序”,其排序方法就是按照上述原则。
最后把排序后的数组依次输出即可。

实现代码如下:

  1. import java.io.IOException;

  2. public class main {

  3.     // if a>b return 1
  4.     // if a==b return 0;
  5.     // if a
  6.     public static int comparestrvalue(String a, String b) {
  7.         int ia =0;
  8.         int ib =0;
  9.         while(ia<a.length() && ib<b.length()){
  10.             if(a.toCharArray()[ia]>b.toCharArray()[ib]){
  11.                 return 1;
  12.             }
  13.             if(a.toCharArray()[ia]<b.toCharArray()[ib]){
  14.                 return -1;
  15.             }
  16.             ia++;
  17.             ib++;
  18.         }
  19.         if( a.length()<b.length()){
  20.             return 1;
  21.         }
  22.         if( a.length()>b.length()){
  23.             return -1;
  24.         }    
  25.         return 0;
  26.     }

  27.     public static void sortinput(String[] input) {
  28.         for (int i = 0; i < input.length - 1; i++) {
  29.             for (int j = 0; j < input.length - i - 1; j++) {
  30.                 if (comparestrvalue(input[j], input[j + 1]) < 0) {
  31.                     String temp = input[j];
  32.                     input[j] = input[j + 1];
  33.                     input[j + 1] = temp;
  34.                 }
  35.             }
  36.         }
  37.     }
  38.     /**
  39.      * @param args
  40.      * @throws Exception
  41.      * @throws IOException
  42.      */
  43.     public static void main(String[] args){
  44.         // TODO Auto-generated method stub
  45.         String[] input = {"8", "99", "10", "3200"};
  46.         sortinput(input);
  47.         for(int i = 0; i<input.length;i++){
  48.             System.out.print(input[i]);
  49.         }
  50.     
  51.     }

  52. }



阅读(2755) | 评论(3) | 转发(1) |
给主人留下些什么吧!~~

w159715972015-10-22 22:08:18

您好,“3”,“34”这种情况按您的算法结果是334,但实际应该是343啊?

runningdark2014-10-11 23:49:28

yimiqidage:这个算法有问题啊:
 "4", "99","8","41","49"
这组数字,使用上面的算法的结果是:  99849414
但是,实际上最大的数字应该是 99849441

诶,一直太忙,今天才看到。"例如9911和,99, 头两位都相等,那么我们选择短的那个"。 4和41比,4要短,所以选择的是4,然后才是441 当然出来是441 而不是414. :)有空就算算,没空就算啦,这题太水了。

回复 | 举报

yimiqidage2014-08-28 10:44:49

这个算法有问题啊:
 "4", "99","8","41","49"
这组数字,使用上面的算法的结果是:  99849414
但是,实际上最大的数字应该是 99849441