首页 > 编程语言 > 详细

剑指Offer——把数组排成最小的数

时间:2019-07-13 22:36:28      阅读:99      评论:0      收藏:0      [点我收藏+]

1、题目描述

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

2、代码实现

package com.baozi.offer;

/**
 * 输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
 * 例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
 *
 * @author BaoZi
 * @create 2019-07-13-22:00
 */
public class Offer25 {
    public static void main(String[] args) {
        Offer25 offer25 = new Offer25();
        int[] array = new int[]{3, 32, 321};
//        String[] chars = new String[]{"c", "cb", "cba"};
        String result = offer25.PrintMinNumber(array);
//        String result1 = offer25.PrintMinNumber(chars);
        System.out.println(result);
//        System.out.println(result1);
    }

    public String PrintMinNumber(String[] numbers) {
        if (numbers.length == 0 || numbers == null) {
            return "";
        }
        int length = numbers.length;
        String[] strs = new String[length];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            strs[i] = numbers[i] + "";
        }
        //重写比较大小的方法
        java.util.Arrays.sort(strs, new java.util.Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                String s1 = o1 + o2;
                String s2 = o2 + o1;
                return s1.compareTo(s2);
            }
        });
        for (int i = 0; i < length; i++) {
            sb.append(strs[i]);
        }
        return sb.toString();
    }

    public String PrintMinNumber(int[] numbers) {
        if (numbers.length == 0 || numbers == null) {
            return "";
        }
        int length = numbers.length;
        String[] strs = new String[length];
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            strs[i] = numbers[i] + "";
        }
        //重写比较大小的方法
        java.util.Arrays.sort(strs, new java.util.Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                String s1 = o1 + o2;
                String s2 = o2 + o1;
                return s1.compareTo(s2);
            }
        });
        for (int i = 0; i < length; i++) {
            sb.append(strs[i]);
        }
        return sb.toString();
    }
}

  

剑指Offer——把数组排成最小的数

原文:https://www.cnblogs.com/BaoZiY/p/11182310.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!