首页 > 试题广场 >

最大数

[编程题]最大数
  • 热度指数:37228 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 256M,其他语言512M
  • 算法知识视频讲解
给定一个长度为n的数组nums,数组由一些非负整数组成,现需要将他们进行排列并拼接,每个数不可拆分,使得最后的结果最大,返回值需要是string类型,否则可能会溢出。

数据范围:
进阶:时间复杂度 ,空间复杂度:
示例1

输入

[30,1]

输出

"301"
示例2

输入

[2,20,23,4,8]

输出

"8423220"
示例3

输入

[2]

输出

"2"
示例4

输入

[10]

输出

"10"

备注:
输出结果可能非常大,所以你需要返回一个字符串而不是整数。
利用冒泡排序进行组合的数字大小比较
class Solution:
    def solve(self , nums ):
        # write code here
        if sum(nums)==0:
            return 0
        for i in range(len(nums) - 1):
            for j in range(i + 1, len(nums)):
                if int(str(nums[i]) + str(nums[j])) < int(str(nums[j]) + str(nums[i])):
                    nums[i], nums[j] = nums[j], nums[i]
        return ''.join(str(i) for i in nums)

发表于 2021-10-18 20:18:09 回复(0)
function solve( nums ) {
    // write code here
  return  nums.sort(function(a,b){
        return (""+b+a)-(""+a+b)
    }).join("").replace(/^0+$/g,"0")
}
// solve([3,30,34,5,9])
module.exports = {
    solve : solve
};
发表于 2021-08-20 15:33:22 回复(0)
一个自定义规则的冒泡排序可以解决该题目
我们把列表里面的每个数字定义为元素
观察题目我们可以得出如下优先级规则:
  1. 列表里面每个元素中第一个数字最大的应该排前面
  2. 第一个数字都相同的情况下,元素长度越短,越应该排前面
  3. 第一个数字都相同,元素长度也相同的情况下,元素化为数字比较,越小的排在后面
只要符合上述条件的任意一个就发生交换
源码如下:
#
# 最大数
# @param nums int整型一维数组 
# @return string字符串
#
class Solution:
    def solve(self , nums ):
        # write code here
        temp=-1
        floor=len(nums)-1
        
        st=list(map(str,nums))
        while floor>0:
            for i in range(floor):
                if st[i][0]<st[i+1][0]:
                    temp=st[i+1]
                    st[i+1]=st[i]
                    st[i]=temp
                elif st[i][0]==st[i+1][0] and len(st[i])>len(st[i+1]):
                    temp=st[i+1]
                    st[i+1]=st[i]
                    st[i]=temp
                elif st[i][0]==st[i+1][0] and len(st[i])==len(st[i+1]) and int(st[i])<int(st[i+1]):
                    temp=st[i+1]
                    st[i+1]=st[i]
                    st[i]=temp
                
            floor-=1
                
        set_st=set(st)#全部是0,则返回0 ‘[0,0,0]’--->0
        if len(set_st)==1 and '0' in set_st:
            return '0'
        
        return ''.join(st)


发表于 2021-07-25 23:08:02 回复(1)
额,没想到 [0,0] 这测试用例,用了个 特判。
其他就用 回溯 挨个 比较出 最大的情况, 没想到就 通过了 哈哈。
class Solution:
    def solve(self , nums ):
        # write code here
        self.res = ''
        n = len(nums)
        def dfs(index, path):
            if index == n:
                tmp = "".join(path)
                if tmp > self.res:
                    self.res = tmp
                return
            for i in range(index, n):
                nums[index], nums[i] = nums[i], nums[index]
                path.append(str(nums[index]))
                dfs(index+1, path)
                path.pop()
                nums[index], nums[i] = nums[i], nums[index] 
        dfs(0, [])
        if int(self.res) == 0:
            return '0'
        return self.res


发表于 2021-01-26 16:43:28 回复(0)
class Solution
{
public:
    /**
     * 最大数
     * @param nums int整型vector
     * @return string字符串
     */
    string solve(vector<int> &nums)
    {
        // write code here
        vector<string> a;
        for (auto &s : nums)
            a.push_back(to_string(s));

        sort(a.begin(), a.end(), cmp);

        string s;
        for (auto &ch : a)
            s = s + ch;

        if (s[0] == '0')
            s = "0";

        return s;
    }

    static bool cmp(string a, string b)
    {
        return a + b > b + a;
    }
};

发表于 2022-03-03 18:43:57 回复(0)

思路:来自于别人的思想,如果有不对的地方请指出

类似于冒泡,从数组中拿出a和b,转化成String,组合成ab,ba然后再转化为整数类型, 比较大小。一只冒泡到最后,把能组成最大值的放在前面,最后全部合起来转化为一个string返回即可。

// 函数入口
public String maxStr(int[] arr){
    // 边界值
    if (arr == null || arr.length == 0) return "";
    // 开始冒泡
    for (int i = 0; i < arr.length - 1; ++i){
        for (int j = 0; j < arr.length - i - 1; ++j){
            // 把int转为String
            String a = String.valueOf(arr[j]); // 也可以直接 arr[j] + "" ,我这里不知道两个的速度比较
            String b = String.valueOf(arr[j + 1]);  // 就随便用了
            String sum1 = a + b,sum2 = b + a;
            if (!compare(sum1,sum2)) {
                // 交换
                swap(arr,j,j + 1);
            }
        }
    } 
    // 换完之后,结果是能组成最大的数都在前面,所以转化为一个String返回即可
    String res = "";
    for (int i = 0; i < arr.length ;++i){
        res += (arr[i] + "");
    }
    return res;
}
// 比较ab,ba大小 ,sum1是  ab ,sum2 是ba
public boolean compare(String sum1, String sum2){
    int i = Integer.parseInt(sum1),j = Integer.parseInt(sum2);
    return i >= j?  true : false;
}
// 交换
public void swap(int[] arr,int i ,int j ){
    int temp = arr[i];
    arr[i] = arr[j];
    arr[j] = temp;
}
编辑于 2020-08-06 19:39:41 回复(1)
class Solution {
public:
    /**
     * 最大数
     * @param nums int整型vector 
     * @return string字符串
     */
    static bool cmp(string &a, string& b){
        return a+b>b+a;
    }
    string solve(vector<int>& nums) {
        // write code here
        vector<string>vec;
        //将整型的数字转化为字符串
        for(int i=0;i<nums.size();i++){
            vec.push_back(to_string(nums[i]));
        }
        //排序
        sort(vec.begin(),vec.end(),cmp);
        if(vec[0]=="0") return "0";
        
        string res="";
        for(int i=0;i<vec.size();i++){
            res+=vec[i];
        }
        return res;
    }
};

发表于 2021-08-11 14:48:29 回复(0)
重写Comparator接口的compare方法。官方API介绍:

比较它的两个参数的顺序。当第一个参数小于、等于或大于第二个参数时,返回一个负整数、零或正整数。

在前面的描述中,符号sgn(表达式)表示数学符号函数,它定义根据表达式的值是负、零还是正返回-1、0或1中的一个。

实现者必须确保所有x和y的sgn(compare(x, y)) == -sgn(compare(y, x))。(这意味着当且仅当compare(y, x)抛出异常时,compare(x, y)必须抛出异常。)

实现者还必须确保关系是可传递的:((compare(x, y)&gt;0) && (compare(y, z)&gt;0))意味着比较(x, z)&gt;0。

最后,实现者必须确保对于所有的z, compare(x, y)==0意味着sgn(compare(x, z))==sgn(compare(y, z))。

通常情况下,但并不严格要求(compare(x, y)==0) == (x = (y))。一般来说,任何违反这一条件的比较国都应明确指出这一事实。推荐的语言是“注意:这个比较器强加的顺序与等号不一致。”

参数:

O1 -第一个被比较的对象。

O2——第二个要比较的物体。

返回:

作为第一个参数的负整数、零或正整数小于、等于或大于第二个参数。

public class Solution {
    /**
     * 最大数
     * @param nums int整型一维数组 
     * @return string字符串
     */
    public String solve (int[] nums) {
        // write code here
        String[] ss = new String[nums.length];
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < nums.length; i++) {
            ss[i] = String.valueOf(nums[i]);
        }
         Arrays.sort(ss, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                return Integer.valueOf(o2 + o1) - Integer.valueOf(o1 + o2);
            }
        });
        if(ss[0].equals("0")) return "0";
        for(int i = 0; i < ss.length; i++) {
            sb.append(ss[i]);
        }
        return sb.toString();
    }
}


发表于 2021-06-17 10:40:24 回复(0)
数组按照字典序进行排序即可,注意返回值为0的情况
class Solution {
public:
    /**
     * 最大数
     * @param nums int整型vector 
     * @return string字符串
     */
    static bool cmp(string a, string b){
        if((a+b) > (b+a)){
            return true;
        }
        else{
            return false;
        }
    }
    string solve(vector<int>& nums) {
        // write code here
        if(nums.size() == 0) return "0";
        vector<string> s;
        for(int i = 0; i < nums.size(); ++i){
            s.push_back(to_string(nums[i]));
        }
        sort(s.begin(), s.end(), cmp);
        if(s[0] == "0") return "0";
        string res = "";
        for(int i = 0; i < s.size(); ++i){
            res += s[i];
        }
        return res;
    }
};





发表于 2021-05-25 17:04:20 回复(0)
#include <stdlib.h>
#include "malloc.h"
#include "string.h"
/**
 * 最大数
 * @param nums int整型一维数组 
 * @param numsLen int nums数组长度
 * @return string字符串
 */
char* solve(int* nums, int numsLen ) {
    // write code here
    char combinea[42] = {0};
    char combineb[42] = {0};
    int i,j,temp = 0;
    int k, g;
    
    for (i = 0; i < numsLen - 1; i++) {
        for (j = 0; j < numsLen - i - 1; j++) {
            (void)sprintf(combinea, "%d%d", nums[j], nums[j+1]);
            (void)sprintf(combineb, "%d%d", nums[j+1], nums[j]);
            k = atoi(combinea);
            g = atoi(combineb);
            if (k < g) {
                temp = nums[j+1];
                nums[j+1] = nums[j];
                nums[j] = temp;
            }
        }
    }
    char *result = (char*)malloc(21*numsLen);
    (void)memset(result, 0, 21*numsLen);
    for (i = 0; i < numsLen; i++) {
        sprintf(combinea, "%d", nums[i]);
        strcat(result, combinea);
    }
    if (result[0] == '0'){
        result[1] = '\0';
    }
    return result;
}
发表于 2021-03-18 23:02:15 回复(0)
/**
 * 最大数
 * @param nums int整型一维数组 
 * @return string字符串
 */

function solve( nums ) {
    // write code here
    nums.sort((a,b)=>{
       let x = '' + a +b
       let y = '' + b + a
       return y-x
    })
  let res = nums.join('')[0] == '0' ?'0':nums.join('') 
  return res
    
}
module.exports = {
    solve
};
发表于 2021-07-28 22:04:58 回复(0)
import java.util.*;


public class Solution {
    /**
     * 最大数
     * @param nums int整型一维数组 
     * @return string字符串
     */
    public String solve (int[] nums) {
        String[] strArr = new String[nums.length];
        for (int i = 0 ; i < nums.length ;i++){
            strArr[i]= String.valueOf(nums[i]);
        }
        Arrays.sort(strArr, (o1, o2) -> Integer.parseInt(o2+o1) - Integer.parseInt(o1+o2));
        StringBuilder maxString = new StringBuilder();
        if(strArr[0].equals( "0")){
            return "0";
        }
        for (int i = 0 ; i < strArr.length;i++){
            
            maxString.append(strArr[i]);
        }
        return maxString.toString();
        // write code here
    }
}


发表于 2020-11-12 22:01:13 回复(0)
# 最终的数据如果从头到尾组合应当符合以下顺序:首先是首数字越大的越靠前,在首字母相同的情况下,长度越短的越靠前,长度也相同的情况下,应当满足值越大的越靠前。
# 根据这一原理,可以根据上面的反序进行排序
# 首先将数据按照从小到大的顺序排序
# 然后将数据按照长短排序
# 最后把数据按照首字母数字排序
class Solution:
    def solve(self , nums ):
        if nums.count(0) == len(nums): return '0'
        else:
            nums.sort(reverse=True)
            nums = list(map(str, nums))
            nums.sort(key=lambda item:len(item))
            nums.sort(reverse=True, key=lambda item:item[0])
            return ''.join(list(map(str, nums)))
发表于 2020-08-20 22:55:18 回复(1)
function solve( nums ) {
    nums.sort((a,b)=>`${b}${a}`-`${a}${b}`)
    return nums[0]?nums.join(''):'0'
}

发表于 2023-06-27 22:30:58 回复(0)

import java.util.*;
 
 
public class Solution {
    /**
     * 最大数
     * @param nums int整型一维数组 
     * @return string字符串
     */
    public String solve (int[] nums) {
        // write code here
        //冒泡排序,降序排列,小的数往后冒
        for(int i = 0; i < nums.length; i++){
            for(int j = 0; j < nums.length - i - 1; j++){
                //数值排序时,考虑十位数与个位数的拼接
                
                //保存拼接的字符串,拼接字符串
                String a = String.valueOf(nums[j]);
                String b = String.valueOf(nums[j+1]);
                String sum1 = a+b,sum2 = b+a;
                
                //转换成基本数据类型才能比较
                int temp1 = Integer.parseInt(sum1),temp2=Integer.parseInt(sum2);
                
                //若temp1>temp2,则说明a(nums[j])在拼接时放在前面,nums[j]与nums[j+1]不用交换
                //若temp1<temp2,则说明b(nums[j+1])在拼接时放在前面,发生交换
                if(temp1<temp2){
                    int temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
        
        String str = new String();
        for(int i = 0; i < nums.length; i++){
            str += nums[i];
        }
        if(str.length()!=0 && str.charAt(0) == '0'){
            return "0";
        }else{
            return str;
        }
         
    }

    
}

发表于 2022-08-16 11:29:09 回复(0)
using System;
using System.Collections.Generic;

class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 最大数
     * @param nums int整型一维数组
     * @return string字符串
     */
    public string solve (List<int> nums) {
        // write code here
        if (nums == null || nums.Count == 0)
            return string.Empty;
        if (nums.Count == 1)
            nums[0].ToString();

        List<string> strNums = new List<string>() { };
        foreach (int val in nums)
            strNums.Add(val.ToString());
        strNums.Sort(StrMax);

        //List<string> strNums = new List<string>() { nums[0].ToString() };
        //for(int nIndex = 1; nIndex < nums.Count; nIndex++)
        //{
        //    //int nFindIndex = strNums.FindIndex(r => string.Compare(r, nums[nIndex].ToString(), true) > 0);
        //    int nFindIndex = strNums.FindIndex(StrMax);
        //    if (nFindIndex >= 0)
        //        strNums.Insert(nFindIndex, nums[nIndex].ToString());
        //    else
        //        strNums.Add(nums[nIndex].ToString());
        //}
        strNums.Reverse();
        return strNums[0].ToString().Equals("0") ? "0" : string.Join("", strNums);
    }

    public static int StrMax(string strA, string strB) {
        if (string.IsNullOrWhiteSpace(strA))
            return -1;
        if (string.IsNullOrWhiteSpace(strB))
            return 1;

        int nIndex = 0;
        for (; nIndex < strA.Length && nIndex < strB.Length; nIndex++) {
            if (strA[nIndex] > strB[nIndex])
                return 1;
            if (strA[nIndex] < strB[nIndex])
                return -1;
        }

        int nRtn = 0;
        if (strA.Length > strB.Length)
            nRtn = strA[nIndex] >= strA[nIndex - 1] ? 1 : strA[nIndex] == strA[nIndex - 1] ?
                   0 : -1;
        else if (strA.Length == strB.Length)
            nRtn = 0;
        else
            nRtn = strB[nIndex] >= strB[nIndex - 1] ? -1 : strB[nIndex] == strB[nIndex - 1]
                   ? 0 : 1;
        return nRtn;
    }
}
发表于 2024-03-29 09:40:46 回复(0)
public String solve (int[] nums) {
    // write code here
    StringBuilder res=new StringBuilder();
    PriorityQueue<Integer> queue=new PriorityQueue<Integer>(new Comparator<Integer>(){
        @Override
        public int compare(Integer num1 ,Integer num2){
            return (num2+""+num1).compareTo(num1+""+num2);
        }
    });
    for(int num:nums){
        queue.add(num);
    }
    while(!queue.isEmpty()){
        res.append(queue.poll());
    }
    return res.charAt(0)=='0'?"0":res.toString();
}

编辑于 2024-03-09 16:46:33 回复(0)
变相的排序问题,只是修改了排序的判定方法
import java.util.*;


public class Solution {
    class AAAA {
        int val;
        String num;
        int length = 0;
        boolean isUesd = false;

        public AAAA(int val) {
            this.val = val;
            this.num = String.valueOf(val);
            this.length = this.num.length();
        }
    }

    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 最大数
     * @param nums int整型一维数组
     * @return string字符串
     */
    public String solve (int[] nums) {
        // write code here
        StringBuilder sb = new StringBuilder();
        AAAA[] res = new AAAA[nums.length];
        for (int i = 0; i < nums.length; i++) {
            res[i] = new AAAA(nums[i]);
        }
        while (true) {
            int index = -1;
            for (int i = 0; i < res.length; i++) {
                if (res[i].isUesd) {
                    continue;
                }
                index = i;
            }
            if (index < 0) break;
            for (int j = 0; j < res.length; j++) {
                if (!res[j].isUesd && compare(res[index], res[j]) < 0) {
                    index = j;
                }
            }
            res[index].isUesd = true;
            if (sb.length() == 0 && res[index].val == 0) {
                continue;
            }
            sb.append(res[index].num);
        }

        if (sb.length() > 0) {
            return sb.toString();
        } else {
            return "0";
        }
    }

    public long compare(AAAA a1, AAAA a2) {
        long n1 = 1, n2 = 1;
        for (int i = 0; i < a2.length; i++) {
            n1 = n1 * 10;
        }
        n1 = n1 * a1.val + a2.val;
        for (int i = 0; i < a1.length; i++) {
            n2 = n2 * 10;
        }
        n2 = n2 * a2.val + a1.val;
        return n1 - n2;
    }
}


发表于 2023-08-19 19:42:21 回复(0)
评论区看到的想法,真牛
class Solution {
  public:
    /**
     * 最大数
     * @param nums int整型vector
     * @return string字符串
     */
    static bool cmp(int a, int b) {
        string ta = to_string(a);
        string tb = to_string(b);
       
        return  ta + tb > tb + ta;
    }
    string solve(vector<int>& nums) {
        string res = "";
        sort(nums.begin(), nums.end(), cmp);
        for (int i = 0; i < nums.size(); i++) {
            res += to_string(nums[i]);
        }
        if(res[0] == '0') return "0";
        return res;
    }
};


发表于 2023-05-15 16:13:55 回复(0)
package main

import "strconv"
import "sort"
import "strings"

/**
 * 最大数
 * @param nums int整型一维数组 
 * @return string字符串
*/
func solve( nums []int ) string {
    arr:=[]string{}
    for _,x:=range nums{
        arr=append(arr,strconv.Itoa(x))
    }
    sort.Slice(arr,func(i,j int)bool{
        if arr[i]+arr[j]>arr[j]+arr[i]{
            return true
        }
        return false
    })
    for arr[0]=="0"&&len(arr)>1{
        arr=arr[1:]
    }
    return strings.Join(arr,"")
}

发表于 2023-03-08 09:06:22 回复(0)