题解 | #最大数#

最大数

http://www.nowcoder.com/practice/fc897457408f4bbe9d3f87588f497729

思路:自定义排序

实现:对于数组中的两个整数,我们自定义他们之间的顺序,可以考虑比较两个数拼接之后的数字,比如x,y,则比较y拼接在x后,和x拼接在y后的大小,实现定制排序。

注意点:在运行过程中遇到了特殊的测试用例[0,0],我们只需要加一个条件(sb.length() == 1 && Integer.parseInt(sb.toString()) == 0 && num == 0 则不加入多余的零即可。

代码

import java.util.*;
public class Solution {
    /**
     * 最大数
     * @param nums int整型一维数组 
     * @return string字符串
     */
    public String solve (int[] nums) {
        Integer[] nums1 = new Integer[nums.length];
        for (int i = 0; i < nums.length; i++) nums1[i] = nums[i];
        Arrays.sort(nums1, new Comparator<Integer>(){
            @Override
            public int compare(Integer x, Integer y){
                long s_x = 1L, s_y = 1L;
                int x_temp = x, y_temp = y;
                while (x_temp != 0){
                    s_x *= 10;
                    x_temp /= 10;
                }
                while (y_temp != 0){
                    s_y *= 10;
                    y_temp /= 10;
                }
                return (int)((y * s_x + x) - (x * s_y + y));
            }
        });
        StringBuilder sb = new StringBuilder();
        for (int num : nums1){
            if (sb.length() == 1 && Integer.parseInt(sb.toString()) == 0 && num == 0) continue;
            sb.append(num);
        }
        return sb.toString();
    }
}
全部评论

相关推荐

程序员牛肉:主要是因为小厂的资金本来就很吃紧,所以更喜欢有实习经历的同学。来了就能上手。 而大厂因为钱多,实习生一天三四百的就不算事。所以愿意培养你,在面试的时候也就不在乎你有没有实习(除非是同级别大厂的实习。) 按照你的简历来看,同质化太严重了。项目也很烂大街。 要么换项目,要么考研。 你现在选择工作的话,前景不是很好了。
点赞 评论 收藏
分享
但听说转正率很低,我现在有在实习了,好纠结要不要去
熬夜脱发码农:转正率低归低,但是实习的经历你可以拿着,又不是说秋招不准备了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务