GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — LeetCode/Greedy/179.Largest-Number at master · wisdompeak/LeetCode

Expand file tree

/

179.Largest-Number

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

179.Largest-Number

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
179.Largest-Number.cpp
179.Largest-Number.cpp
 
 
Readme.md
Readme.md
 
 

Readme.md

179.Largest-Number

本题的本质是一个非常有用的知识点:给你一个字符串数组,如何排序拼接这些字符串实现字典序最大?方法是设计一个巧妙的排序函数:

static bool cmp(string a, string b)
{
    string c=a+b;
    string d=b+a;
    return stoll(c)>stoll(d);
}

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

将以此排序的字符串拼接起来,就是字典序最大的!

证明:

  1. 传递性
    我们试图证明如果s3>s2,且s2>s1,那么就一定共有s3>s1. 因为只有具备传递性的大小比较,才能将所有的字符串的唯一排序。

我们令s3、s2、s1的长度对应的10的幂分别是n3、n2、n1(比如说1000,100,10),那么就有

s3 > s2 => s3s2 > s2s3 => s3*n2+s2 > s2*n3+s3 => s3(n2-1) > s2(n3-1)
s2 > s1 => s2s1 > s1s2 => s2*n1+s1 > s1*n2+s2 => s2(n1-1) > s1(n2-1)

因为所有的都是非负数,所以有

s3s2(n2-1)(n1-1) > s2s1(n3-1)(n2-1)

如果s2!=0,那么得到s3(n1-1)>s1(n3-1) => s3n1+s1 > s1n3+s3,即 s3>s1
如果s2==0,那么s1==0,必然有 s3>s1

  1. 算法的正确性
    对于任意一个乱序的字符串数组,我们都可以通过交换一对相邻的逆序对来实现“冒泡”排序。比如
s3s1s2s4
s3s1s4s2
s3s4s1s2
s4s3s1s2
s4s3s2s1

在每一步中,只有一对相邻的字符串做了交换,每次交换的过程中都是将较大的si移动到较小的sj的前面,即由...sjsi....变成了...sisj....。显然我们发现这一步变化是将整体的字符串的字典序变大的。于是我们推断出每一步变化都是将这个字符串的字典序变大。也就是说,任意一个乱序拼接的字符串,都不如按照排序函数得到顺序拼接的字符串大。

You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.