From d145d689c20b22fc560d7d9384b1b813d04e589b Mon Sep 17 00:00:00 2001 From: Omooo <869759698@qq.com> Date: Fri, 12 Jun 2020 09:02:37 +0800 Subject: [PATCH] =?UTF-8?q?Update=20=E6=95=B0=E7=BB=84=E7=9B=B8=E5=85=B3.m?= =?UTF-8?q?d?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- blogs/Algorithm/剑指 Offer/数组相关.md | 52 ++++++++++++++++++++ 1 file changed, 52 insertions(+) diff --git a/blogs/Algorithm/剑指 Offer/数组相关.md b/blogs/Algorithm/剑指 Offer/数组相关.md index b787648..431f506 100644 --- a/blogs/Algorithm/剑指 Offer/数组相关.md +++ b/blogs/Algorithm/剑指 Offer/数组相关.md @@ -159,3 +159,55 @@ class Solution { } ``` +[45. 把数组排成最小的数](https://leetcode-cn.com/problems/ba-shu-zu-pai-cheng-zui-xiao-de-shu-lcof/) + +```java +class Solution { + public String minNumber(int[] nums) { + String[] strings = getStringArray(nums); + Arrays.sort(strings, new Cop()); + + StringBuilder result = new StringBuilder(); + for (String s : strings) { + result.append(s); + } + return result.toString(); + } + + private String[] getStringArray(int[] nums) { + String[] strings = new String[nums.length]; + for (int i = 0; i < nums.length; i++) { + strings[i] = String.valueOf(nums[i]); + } + return strings; + } + + class Cop implements Comparator { + @Override + public int compare(String o1, String o2) { + String s1 = o1 + o2; + String s2 = o2 + o1; + return s1.compareTo(s2); + } + } +} +``` + +```java +class Solution { + public String minNumber(int[] nums) { + String[] strings = new String[nums.length]; + for (int i = 0; i < nums.length; i++) { + strings[i] = String.valueOf(nums[i]); + } + Arrays.sort(strings, (o1, o2) -> (o1 + o2).compareTo(o2 + o1)); + + StringBuilder result = new StringBuilder(); + for (String s : strings) { + result.append(s); + } + return result.toString(); + } +} +``` +