算法——把数组排成最小的数

输入一个非负整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。
leetcode

解题思路:对数组进行重新排序,排序规则是,分别将两个数值放在前后位置,然后比较作为返回。

class Solution {
    public String minNumber(int[] nums) {
        PriorityQueue<Integer> q = new PriorityQueue<>((a, b) -> {
            String i = String.valueOf(a) + String.valueOf(b), j = String.valueOf(b) + String.valueOf(a);
            if(i.compareTo(j) > 0) return 1;
            else return -1;
        });

        for(int n : nums) {
            q.offer(n);
        }
        
        StringBuilder res = new StringBuilder();

        while(!q.isEmpty()) {
            res.append(q.poll());
        }

        return res.toString();
    }
}
原文地址:https://www.cnblogs.com/lippon/p/14117664.html