剑指Offer 33 把数组排成最小的数
2017-03-31 21:25
225 查看
题目描述
输入一个正整数数组,把数组里所有数字拼接起来排成一个数,打印能拼接出的所有数字中最小的一个。例如输入数组{3,32,321},则打印出这三个数字能排成的最小数字为321323。思路
首先想到的是自然是暴力全拍列;然后想到了变成字符,通过Collections.sort()排序,后来发现,是数组;也就是说(3,32)只能组成332或者323;这个想法是不对的
于是自然也就想到了,对每两个数变成string来比较,但是不会写。。。。然后就发现人家的代码是重写了sort方法,简单来说就是
代码
static public String PrintMinNumber(int [] numbers) { int length ; String s = ""; ArrayList<Integer> li 4000 st = new ArrayList<>(); length = numbers.length; for (int i = 0 ; i <length; i++) { list.add(numbers[i]); } Collections.sort(list, new Comparator<Integer>() { //重写sort的函数 @Override public int compare(Integer o1, Integer o2) { //重写sort实际上是重写了Comparator<>接口中的compare而已 String s1 = o1+""+o2; String s2 = o2+""+o1; return s1.compareTo(s2); //这里比较方便的借用了compareTo函数,其实可以自己写 } }); for (int j :list) { s+=j; } return s; }
收获
重写了Collections.sort中的Comparator中的compare,还是用厉害的第一次见到这种接口当做参数的
相关文章推荐
- 剑指offer 面试33 把数组排成最小的数
- 剑指Offer面试题33把数组排成最小的数,面试题34丑数
- 剑指offer-面试题33:把数组排成最小的数
- 【剑指offer-解题系列(33)】把数组排成最小的数
- 剑指Offer:面试题33 把数组排成最小的数
- 剑指offer 面试题33—把数组排成最小的数
- 剑指offer 33 把数组排成最小的数
- 【剑指Offer学习】【面试题33:把数组排成最小的数】
- 剑指offer-面试题33-把数组排成最小的数
- 剑指offer 面试题33 数组组合的最小数
- 【剑指Offer学习】【面试题33:把数组排成最小的数】
- 剑指offer--面试题33:把数组排成最小的数
- 剑指offer33 把数组排成最小的数
- 剑指offer33:把数组排成最小的数
- 剑指Offer——面试题33:把数组排成最小的数
- 剑指Offer----面试题33:把数组排成最小的数
- 【剑指offer】题33:数组排成最小的数
- 剑指offer 33 把数组排成最小的数
- 剑指offer面试题33:把数组排成最小的数
- 【剑指Offer】面试题33:把数组排成最小的数