• 32把数组排成最小的数


    题目描述

    输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。

    思路:

    在这里自定义一个比较大小的函数,比较两个字符串s1, s2大小的时候,先将它们拼接起来,比较s1+s2,和s2+s1那个大,如果s1+s2大,那说明s2应该放前面,所以按这个规则,s2就应该排在s1前面。

    需要注意的是可能会有数值溢出,所以转化成字符串来处理。

    思路1 :用冒泡直接解

     1 import java.util.ArrayList;
     2 import java.util.Comparator;
     3 public class Solution {
     4     public String PrintMinNumber(int [] numbers) {
     5         String res = "";
     6         for(int i = 0;i<numbers.length;i++){
     7             for(int j = 0;j<numbers.length-i-1;j++){
     8                 if(compare(numbers[j],numbers[j+1])>0)
     9                     swap(numbers,j,j+1);
    10             }
    11         }
    12         for(int i=0;i<numbers.length;i++){
    13             res+=numbers[i]+"";
    14         }
    15         return res;
    16     }
    17     private void swap(int[] a,int i ,int j){
    18         int temp = a[i];
    19         a[i] = a[j];
    20         a[j] = temp;
    21     }
    22     private int compare(Integer s1,Integer s2){
    23         return (s1+""+s2).compareTo((s2+""+s1));
    24     }
    25 }
    思路2:用java中的已经存在的排序函数

     1 import java.util.ArrayList;
     2 import java.util.Comparator;
     3 import java.util.Collections;
     4 public class Solution {
     5     public String PrintMinNumber(int [] numbers) {
     6         String res = "";
     7         ArrayList<Integer> num = new ArrayList<Integer>();
     8         for(int i = 0;i<numbers.length;i++)
     9             num.add(numbers[i]);
    10         Collections.sort(num,new Comparator<Integer>(){
    11         public int compare(Integer s1,Integer s2){
    12         return (s1+""+s2).compareTo((s2+""+s1));}
    13         });
    14         for(int j:num){
    15             res+=j+"";
    16         }
    17         return res;
    18     }
    19  
    20     
    21 }
    
    
    
     
















    c++ :

     1 class Solution {
     2 public:
     3     static bool cmp(int a,int b){
     4         return to_string(a)+to_string(b)<to_string(b)+to_string(a);
     5     }
     6 
     7     string PrintMinNumber(vector<int> numbers) {
     8         string res = "";
     9         sort(numbers.begin(),numbers.end(),cmp);
    10         for(int i =0;i<numbers.size();i++){
    11             res+=to_string(numbers[i]);
    12         } 
    13         return res;
    14     }
    15     
    16 };
    
    
    
     
  • 相关阅读:
    批量创建账号脚本
    shell 批量创建_备份 mysql 数据库 表
    优化chkconfig
    cut 命令
    Shell for 循环
    while 读取文件内容
    生成随机数
    linux 资源管理
    shell 脚本后台运行知识
    while 语句
  • 原文地址:https://www.cnblogs.com/zle1992/p/8047666.html
Copyright © 2020-2023  润新知