剑指offer 45题解

题目描述

把数组排成最小的数

解题思路

* 解题思路:
 * 先将整型数组转换成String数组,然后将String数组排序,最后将排好序的字符串数组拼接出来。关键就是制定排序规则。
 * 排序规则如下:
 * 若ab > ba 则 a > b,
 * 若ab < ba 则 a < b,
 * 若ab = ba 则 a = b;
 * 解释说明:
 * 比如 "3" < "31"但是 "331" > "313",所以要将二者拼接起来进行比较
public String PrintMinNumber(int [] numbers) {
        if(numbers == null || numbers.length == 0) return "";
        int len = numbers.length;
        String[] str = new String[len];
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < len; i++){
            str[i] = String.valueOf(numbers[i]);
        }
        Arrays.sort(str,new Comparator<String>(){
            @Override
            public int compare(String s1, String s2) {
                String c1 = s1 + s2;
                String c2 = s2 + s1;
                return c1.compareTo(c2);
            }
        });
        for(int i = 0; i < len; i++){
            sb.append(str[i]);
        }
        return sb.toString();
    }

更加简洁的代码

public String PrintMinNumber(int[] numbers)
{
    if (numbers == null || numbers.length == 0)
        return "";
    int n = numbers.length;
    String[] nums = new String[n];
    for (int i = 0; i < n; i++)
        nums[i] = numbers[i] + "";
    Arrays.sort(nums, (s1, s2) -> (s1 + s2).compareTo(s2 + s1));
    String ret = "";
    for (String str : nums)
        ret += str;
    return ret;
}

python3 取消了sorted函数里面cmp参数,有点蛋疼
找了好久,有一个优雅的写法

from functools import cmp_to_key
nums = [123,32,11,34]
cmp2key = cmp_to_key(lambda x,y: int(y+x)-int(x+y))
print( ''.join(sorted(map(str, nums), key=cmp2key)))

python2

# -*- coding:utf-8 -*-
class Solution:
    def PrintMinNumber(self, numbers):
        # write code here
        temp = [str(x) for x in sorted(numbers, cmp=self.tem)]
        return ''.join(temp)


    def tem(self,a,b):
        if str(a)+str(b) > str(b)+str(a):
            return 1;
        elif str(a)+str(b) < str(b) +str(a):
            return -1;
        else:
            return 0;

猜你喜欢

转载自blog.csdn.net/ding_xiaofei/article/details/81118994