# 179.Largest-Number

## 179. Largest Number

## 题目地址

<https://leetcode.com/problems/largest-number/>

## 题目描述

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

Example 1:
Input: [10,2]
Output: "210"

Example 2:
Input: [3,30,34,5,9]
Output: "9534330"

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

## 代码

### Approach #1  Sorting via Custom Comparator

```java
class Solution {
  public String largestNumber(int[] nums) {
        String[] asStrs = new String[nums.length];
    for (int i = 0; i < nums.length; i++) {
      asStrs[i] = String.valueOf(nums[i]);
    }

    Arrays.sort(asStrs, new LargerNumberComparator());

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

    String largestNumberStr = new String();
    for (String numAsStr : asStrs) {
      largestNumStr += numAsStr;
    }

    return largestNumberStr;
  }

  private class LargerNumberComparator implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
      String order1 = a + b;
      String order2 = b + a;
      return order2.compareTo(order1);
    }
  }

}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://wentao-shao.gitbook.io/leetcode/graph-search/179.largest-number.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
