[编程题]把数组排成最小的数

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

public class Solution {
public String PrintMinNumber(int [] numbers) {
int n;
String s="";
ArrayList<Integer> list= new ArrayList<Integer>();
n=numbers.length;
for(int i=0;i<n;i++){

}
Collections.sort(list, new Comparator<Integer>(){

public int compare(Integer str1,Integer str2){
String s1=str1+""+str2;
String s2=str2+""+str1;
return s1.compareTo(s2);
}
});

for(int j:list){
s+=j;
}
return s;

}
}

```/*对vector容器内的数据进行排序，按照 将a和b转为string后
若 a＋b<b+a  a排在在前 的规则排序,
如 2 21 因为 212 < 221 所以 排序后为 21 2
to_string() 可以将int 转化为string
*/ class Solution {
public:
static bool cmp(int a,int b){
string A="";
string B="";
A+=to_string(a);
A+=to_string(b);
B+=to_string(b);
B+=to_string(a);

return A<B;
}
string PrintMinNumber(vector<int> numbers) {
sort(numbers.begin(),numbers.end(),cmp);
for(int i=0;i<numbers.size();i++){
}
}
};```

``` * 解题思路：
* 先将整型数组转换成String数组，然后将String数组排序，最后将排好序的字符串数组拼接出来。关键就是制定排序规则。
* 排序规则如下：
* 若ab > ba 则 a > b，
* 若ab < ba 则 a < b，
* 若ab = ba 则 a = b；
* 解释说明：
* 比如 "3" < "31"但是 "331" > "313"，所以要将二者拼接起来进行比较
public String PrintMinNumber(int [] numbers) {
if(numbers == null || numbers.length == 0) return "";
int len = numbers.length;
String[] str = new String[len];
StringBuilder sb = new StringBuilder();
for(int i = 0; i < len; i++){
str[i] = String.valueOf(numbers[i]);
}
Arrays.sort(str,new Comparator<String>(){
@Override
public int compare(String s1, String s2) {
String c1 = s1 + s2;
String c2 = s2 + s1;
return c1.compareTo(c2);
}
});
for(int i = 0; i < len; i++){
sb.append(str[i]);
}
return sb.toString();
}```

```public class Solution {
public String PrintMinNumber(int [] numbers) {
String str = "";
for (int i=0; i<numbers.length; i++){
for (int j=i+1; j<numbers.length; j++){
int a = Integer.valueOf(numbers[i]+""+numbers[j]);
int b = Integer.valueOf(numbers[j]+""+numbers[i]);
if (a > b){
int t = numbers[i];
numbers[i] = numbers[j];
numbers[j] = t;
}

}
}
for (int i = 0; i < numbers.length; i++) {
str += String.valueOf(numbers[i]);
}
return str;
}
}```

```//more about lambda,you can reference:http://blog.csdn.net/taoyanqi8932/article/details/52541312
class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
sort(numbers.begin(),numbers.end(),[](const int& a,const int& b){
string res;
for (auto c:numbers)
res+=to_string(c);
return res;
}
};```

```class Solution {
public:
static bool compare( const string &st1,const string &st2){
string s1 = st1+st2;
string s2 = st2+st1;
return s1<s2;
}
string PrintMinNumber(vector<int> numbers) {
string result;
if(numbers.size()<=0){
return result;
}
vector<string> strNum;
for(int i=0;i<numbers.size();i++ ){
stringstream ss;
ss<<numbers[i];
string s = ss.str();
strNum.push_back(s);
}
sort(strNum.begin(),strNum.end(),compare);

for(int i=0;i<strNum.size();i++){
result.append(strNum[i]);
}
return result;

}
};```

# python solution:

``````# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers:return ""
numbers = list(map(str,numbers))
numbers.sort(cmp=lambda x,y:cmp(x+y,y+x))
return '0' if numbers[0]=='0' else ''.join(numbers)
``````

``````class Solution:
def PrintMinNumber(self, numbers):
# write code here
if not numbers: return ""
numbers = list(map(str, numbers))
numbers.sort(cmp=lambda x, y: cmp(x + y, y + x))
return "".join(numbers).lstrip('0') or'0'
``````

```

```class Solution {
public:
//如果题目要求得出最大的数字，可以将比较器转换成从大到小排序即可
//其中，数字转化为字符串的使用方法，参考别人的代码%>_<%
static int compare(const string& st1,const string& st2)
{
string s1=st1+st2;
string s2=st2+st1;
return s1<s2;//降序排列，改为大于就是升序排列！！！
}
string PrintMinNumber(vector<int> numbers) {
string result;
if(numbers.size()<=0) return result;
vector<string> vec;
for(unsigned int i=0;i<numbers.size();i++)
{
stringstream ss;//使用输入输出流，头文件要包含#include<sstream>
ss<<numbers[i];//读入数字给流处理
string s = ss.str();//转换成字符串
vec.push_back(s);//将字符串s压入vec中
}
//排序，传入比较器，从小到大排序
sort(vec.begin(),vec.end(),compare);
for(unsigned int i=0;i<vec.size();i++)
{
result.append(vec[i]);//拼接字符串，这就是最小的数字
}
return result;
}
};```

```string itos(int x){
return (x > 9 ? itos(x / 10) : "") + char(x % 10 + '0');
}
bool cmp(int a, int b){
return itos(a) + itos(b) < itos(b) + itos(a);
}
class Solution {
public:
string PrintMinNumber(vector<int> a) {
sort(a.begin(), a.end(), cmp);
string s = "";
for(int i = 0; i < int(a.size()); ++i) s += itos(a[i]);
return s;
}
};```

```class Solution {
public:
string PrintMinNumber(vector<int> numbers){
string ret;
vector<string> numbers_str;
for(int i = 0; i < numbers.size(); ++i)
numbers_str.push_back(to_string(numbers[i]));
sort(numbers_str.begin(), numbers_str.end(), MyCompare);
for(int i = 0; i < numbers_str.size(); ++i)
ret += numbers_str[i];
return ret;
}
private:
static bool MyCompare(const string &str1, const string &str2){
return str1 + str2 < str2 + str1;
}
};```

```#Python版
#使用自定义的排序方法
#
# -*- coding:utf-8 -*-
class Solution:
def compare(self,num1,num2):
t = str(num1)+str(num2)
s = str(num2)+str(num1)
if t>s:
return 1
elif t<s:
return -1
else:
return 0

def PrintMinNumber(self, numbers):
# write code here
if numbers is None:
return ""
lens = len(numbers)
if lens ==0 :
return ""
tmpNumbers = sorted(numbers,cmp=self.compare)
return int(''.join(str(x)for x in tmpNumbers))

print Solution().PrintMinNumber([3,32,321])```

``````class Solution {
public:
static bool cmp(int x, int y){
}

string PrintMinNumber(vector<int> numbers) {
sort(numbers.begin(), numbers.end(), cmp);
string ans = "";
for(int i = 0; i < numbers.size(); i++)
ans += to_string(numbers[i]);
return ans;
}
};
``````

JS又来啦啦啦

```function PrintMinNumber(numbers)
{
numbers.sort(function(s1,s2){
let c1=s1+""+s2;
let c2=s2+""+s1;
return c1>c2;
});
let min="";
numbers.forEach(i=>min+=i)
return min;
}
```

```// 利用lambda的简洁解法
import java.util.*;
public class Solution {
public String PrintMinNumber(int [] numbers) {
String[] strs = new String[numbers.length];
for(int i = 0; i < numbers.length; i++)
strs[i] = String.valueOf(numbers[i]);
return Arrays.stream(strs)
.sorted((x, y) -> (x + y).compareTo(y + x))
.reduce("", (x, y) -> x + y);
}
}```

```package com.code.offer;

import java.util.*;

/**
* Created by jiangchao on 2016/10/9.
*/
public class Solution32 {
public String PrintMinNumber(int [] numbers) {
if (numbers == null || numbers.length == 0) return "";
MyComparator myComparator = new MyComparator();
List<Integer> list = new ArrayList<Integer>();
for (int i : numbers) {
}
Collections.sort(list, myComparator);
StringBuilder sb = new StringBuilder();
for (Integer val : list) {
sb.append(val);
}
return sb.toString();
}

private class MyComparator implements Comparator<Integer> {

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

```import java.util.ArrayList;

import java.util.ArrayList;

public class Solution {
public String PrintMinNumber(int [] numbers) {
if(numbers==null||numbers.length==0)
return "";
if(numbers.length==1)
return ""+numbers[0];
String[] str = new String[numbers.length];

for(int i = 0;i<numbers.length;i++){
str[i] = ""+numbers[i];
}
sort(str);
StringBuffer sb = new StringBuffer();
for(int i = 0;i<str.length;i++){
sb.append(str[i]);
}
return sb.toString();
}

private void sort(String[] s){
for(int i = 0;i<s.length-1;i++){
boolean flag = true;
for(int j = 0;j<s.length-i-1;j++){
if((s[j]+s[j+1]).compareTo(s[j+1]+s[j])>0){
String t = s[j+1];
s[j+1] = s[j];
s[j] = t;
flag = false;
}
}
if(flag)
return;
}

}
}```

python solution

```# -*- coding:utf-8 -*-
class Solution:
def PrintMinNumber(self, numbers):
if not numbers:
return ""
numbers = sorted(numbers)  # 这一行不加也能过，但是最好加上
max_number = max(numbers)
len_max = len(str(max_number))
new_numbers = []
for num in numbers:
new_num_str = num
for i in range(len_max-len(str(num))):
new_num = int(new_num_str)
new_numbers.append(new_num)
# 冒泡排序
for i in range(len(new_numbers)-1):
for j in range(len(new_numbers)-i-1):
if new_numbers[j] > new_numbers[j+1]:
new_numbers[j],new_numbers[j+1] = new_numbers[j+1],new_numbers[j]
numbers[j],numbers[j+1] = numbers[j+1],numbers[j]
result = ""
for num in numbers:
result += str(num)
return result```

import itertools
class Solution:
def PrintMinNumber(self, numbers):
# write code here
res = []
if len(numbers) == 0:
return ""
for i in itertools.permutations(numbers):
temp = 0
for x in i:
temp = temp * (10**len(str(x))) + x
res.append(temp)
return min(res)

bool compare(int m, int n) //定义sort中的比较规则
{
string mn = to_string(m) + to_string(n);
string nm = to_string(n) + to_string(m);
if(strcmp(mn.c_str(), nm.c_str()) > 0) //m>n
return false;
else
return true;
}

class Solution
{
public:
string PrintMinNumber(vector numbers)
{
string ret;
if(numbers.size() == 0)
return ret;
sort(numbers.begin(), numbers.end(), compare);
for(int i = 0; i < numbers.size(); i++)
{
ret = ret + to_string(numbers[i]);
}
return ret;
}

};

```class Solution {
public:
string PrintMinNumber(vector<int> numbers) {
if (numbers.empty())
{
return string();
}
string res;
vector<string> strNum(numbers.size());
for (size_t i = 0; i < numbers.size(); i++)
{
stringstream ss;
ss << numbers[i];
strNum[i].append(ss.str());
}
sort(strNum.begin(), strNum.end(), [=](string a, string b) {
string s1 = a + b;
string s2 = b + a;
return s2 > s1;
});
for (int i = 0; i<strNum.size(); i++) {
res.append(strNum[i]);
}
return res;```

``` }
};```

```public String PrintMinNumber(int [] numbers) {
ArrayList<Integer> list = new ArrayList();

list.sort((str1, str2) -> {
String s1 = str1 + "" + str2;
String s2 = str2 + "" + str1;
return s1.compareTo(s2);
});

String s = "";
for (int j : list) {
s += j;
}

return s;
}```

892条回答 95354浏览

# 通过挑战的用户

• 2019-10-17 03:11:16
• 2019-10-17 01:46:05
• 2019-10-16 23:52:18
• 2019-10-16 23:04:35
• 2019-10-16 22:51:20

# 相关试题

• 扫描二维码，关注牛客网

• 下载牛客APP，随时随地刷题