把数组排成最小的数

2020-07-28  本文已影响0人  Crazy_Bear
import java.util.*;

public class Solution {
    public String PrintMinNumber(int [] numbers) {
        ArrayList<Integer> list = new ArrayList<>();
        for(int i = 0 ;i<numbers.length; i++){
            list.add(numbers[i]);
        }
        Collections.sort(list, (a, b) -> {
            String s1 = String.valueOf(a);
            String s2 = String.valueOf(b);
            return (s1+s2).compareTo(s2+s1);
        });
        String res = "";
        for(int ch:list){
            res += String.valueOf(ch);
        }
        return res;
    }
}
class Solution {
public:
    string PrintMinNumber(vector<int> numbers) {
        string res = "";
        if(numbers.empty()) return res;
        sort(numbers.begin(),numbers.end(),cmp);
        for(int i = 0; i<numbers.size(); i++){
            res += to_string(numbers[i]);
        }
        return res;
    }
    
    static bool cmp(int a, int b){
        string c = to_string(a) + to_string(b);
        string d = to_string(b) + to_string(a);
        return c < d;
    }
};
上一篇下一篇

猜你喜欢

热点阅读