179:最大数

This commit is contained in:
huangge1199 2021-04-13 08:40:12 +08:00
parent f7c0812129
commit c58574cb15
4 changed files with 135 additions and 2 deletions

View File

@ -0,0 +1,91 @@
//给定一组非负整数 nums重新排列每个数的顺序每个数不可拆分使之组成一个最大的整数
//
// 注意输出结果可能非常大所以你需要返回一个字符串而不是整数
//
//
//
// 示例 1
//
//
//输入nums = [10,2]
//输出"210"
//
// 示例 2
//
//
//输入nums = [3,30,34,5,9]
//输出"9534330"
//
//
// 示例 3
//
//
//输入nums = [1]
//输出"1"
//
//
// 示例 4
//
//
//输入nums = [10]
//输出"10"
//
//
//
//
// 提示
//
//
// 1 <= nums.length <= 100
// 0 <= nums[i] <= 109
//
// Related Topics 排序
// 👍 542 👎 0
package leetcode.editor.cn;
import java.util.Arrays;
//179:最大数
public class LargestNumber {
public static void main(String[] args) {
//测试代码
Solution solution = new LargestNumber().new Solution();
solution.largestNumber(new int[]{10, 2});
}
//力扣代码
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public String largestNumber(int[] nums) {
int n = nums.length;
// 转换成包装类型以便传入 Comparator 对象此处为 lambda 表达式
Integer[] numsArr = new Integer[n];
for (int i = 0; i < n; i++) {
numsArr[i] = nums[i];
}
Arrays.sort(numsArr, (x, y) -> {
long sx = 10, sy = 10;
while (sx <= x) {
sx *= 10;
}
while (sy <= y) {
sy *= 10;
}
return (int) (-sy * x - y + sx * y + x);
});
if (numsArr[0] == 0) {
return "0";
}
StringBuilder ret = new StringBuilder();
for (int num : numsArr) {
ret.append(num);
}
return ret.toString();
}
}
//leetcode submit region end(Prohibit modification and deletion)
}

View File

@ -0,0 +1,42 @@
<p>给定一组非负整数 <code>nums</code>,重新排列每个数的顺序(每个数不可拆分)使之组成一个最大的整数。</p>
<p><strong>注意:</strong>输出结果可能非常大,所以你需要返回一个字符串而不是整数。</p>
<p> </p>
<p><strong>示例 1</strong></p>
<pre>
<strong>输入<code></code></strong><code>nums = [10,2]</code>
<strong>输出:</strong><code>"210"</code></pre>
<p><strong>示例 2</strong></p>
<pre>
<strong>输入<code></code></strong><code>nums = [3,30,34,5,9]</code>
<strong>输出:</strong><code>"9534330"</code>
</pre>
<p><strong>示例 3</strong></p>
<pre>
<strong>输入<code></code></strong>nums = [1]
<strong>输出:</strong>"1"
</pre>
<p><strong>示例 4</strong></p>
<pre>
<strong>输入<code></code></strong>nums = [10]
<strong>输出:</strong>"10"
</pre>
<p> </p>
<p><strong>提示:</strong></p>
<ul>
<li><code>1 <= nums.length <= 100</code></li>
<li><code>0 <= nums[i] <= 10<sup>9</sup></code></li>
</ul>
<div><div>Related Topics</div><div><li>排序</li></div></div>\n<div><li>👍 542</li><li>👎 0</li></div>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long