Algorithm learning-splicing to the largest number
Question
This is the question I saw when writing LeetCode Largest Number.
The question is to give you a set of numbers, for example:
[3, 30, 34, 5, 9]
The maximum number that can be spelled out is:
9534330
Solutions
In fact, we can easily find that we can sort the numbers according to the desired size.
First, let's look at how to compare. Generally, our idea is to compare directly or compare by bit. However, there are too many situations, such:a=3; b=4It is easy to geta < bAssume thata = 5; b = 34Rathera > bBecause534 > 345. There are other cases. It is too difficult to separate the discussions. We can simply compare them:
Directly compare the two join results of two numbers, for example:a = 45; b = 56;Direct comparison4556 < 5645In this way, the comparison is successful. However, note thatWe need to convert to a string first.Then compare the two numbers, because the joining of the two numbers may be out of the Integer Range.
Code Implementation
The following is a code implementation.
Class Solution {public: string largestNumber (vector
& Num) {string s = ""; sort (num. begin (), num. end (), max); // STL sorting algorithm if (num [0] = 0) {return "0" ;}for (int I = 0; I <num. size (); I ++) {s. append (to_string (num [I]);} return s;} static bool max (int a, int B) {// must be declared as static string s1 = to_string () + to_string (B); string s2 = to_string (B) + to_string (a); return (s1.compare (s2)> 0 );}};
The returned value is the largest number after splicing. It is represented by a string to prevent the value from being expressed beyond the Integer Range.
Do not understand the codesort()For the use of that function, please refer to my other blog: Use of STL sorting function sort
The input value here isvectorContainer. You can think of it as an array for the time being.vectorContainer implementation.