输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。
1 # -*- coding:utf-8 -*- 2 class LargerNum(str): 3 def __lt__(x,y): 4 return x+y < y+x 5 class Solution: 6 def PrintMinNumber(self, numbers): 7 if len(numbers) == 0: 8 return '' 9 numbers = [str(num) for num in numbers] 10 numbers.sort(key = LargerNum) 11 return '0' if numbers[0] == '0' else ''.join(numbers) 12 # write code here
leetcode地址,Java版代码:
1 class Solution { 2 public String minNumber(int[] nums) { 3 int n = nums.length; 4 String[] strNumStrings = new String[n]; 5 for (int i = 0; i < n; i++) { 6 strNumStrings[i] = nums[i] + ""; 7 } 8 Arrays.sort(strNumStrings, new Comparator<String>() { 9 @Override 10 public int compare(String o1, String o2) { 11 Long n1 = Long.valueOf(o1.concat(o2)); 12 Long n2 = Long.valueOf(o2.concat(o1)); 13 if (n1 < n2) { 14 return -1; 15 } else if (n1 >= n2) { 16 return 1; 17 } else { 18 return 0; 19 } 20 } 21 }); 22 StringBuilder stringBuilder = new StringBuilder(); 23 for (int i = 0; i < n; i++) { 24 stringBuilder.append(strNumStrings[i]); 25 } 26 return stringBuilder.toString(); 27 } 28 }