TypechoJoeTheme

IT技术分享

统计

[LeetCode 179] Largest Number [Java] [Beats : 99.87%]

2017-08-12
/
0 评论
/
570 阅读
/
正在检测是否收录...
08/12

1. Description

Given a list of non negative integers, arrange them such that they form the largest number.

Note: The result may be very large, so you need to return a string instead of an integer.

2. Runtime Distribution

3. Submission Details

4. Example

given [3, 30, 34, 5, 9], the largest formed number is 9534330.

5. Code

public String largestNumber(int[] nums)
{
    if (nums == null || nums.length == 0) {
        return "";
    }

    String[] array = new String[nums.length];
    for (int i = 0; i < nums.length; i++) {
        array[i] = String.valueOf(nums[i]);
    }

    Arrays.sort(array, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2)
        {
            String str1 = o1 + o2;
            String str2 = o2 + o1;
            return str2.compareTo(str1);
        }
    });

    if ("0".equals(array[0])) {
        return "0";
    }

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < array.length; i++) {
        sb.append(array[i]);
    }

    return sb.toString();
}

6.Test

import java.util.Arrays;
import java.util.Comparator;

public class LeetCode0179 {
    public String largestNumber(int[] nums)
    {
        if (nums == null || nums.length == 0) {
            return "";
        }

        String[] array = new String[nums.length];
        for (int i = 0; i < nums.length; i++) {
            array[i] = String.valueOf(nums[i]);
        }

        Arrays.sort(array, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2)
            {
                String str1 = o1 + o2;
                String str2 = o2 + o1;
                return str2.compareTo(str1);
            }
        });

        if ("0".equals(array[0])) {
            return "0";
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
        }

        return sb.toString();
    }

    public static void main(String[] args)
    {
        int[] nums = new int[] { 3, 30, 34, 5, 9 };
        LeetCode0179 leetcode = new LeetCode0179();
        System.out.println(leetcode.largestNumber(nums));
    }
}
Math
朗读
赞 · 0
版权属于:

IT技术分享

本文链接:

https://idunso.com/archives/702/(转载时请注明本文出处及文章链接)