How can I manipulate an array to make the largest number?

前端 未结 16 2539
暖寄归人
暖寄归人 2021-01-30 02:47

Say you have an array of positive integers, manipulate them so that the concatenation of the integers of the resultant array is the largest number possible. Ex: {9,1,95,17,5}, r

16条回答
  •  忘掉有多难
    2021-01-30 03:11

    As others have pointed out, a lexicographic sort and concatenation is close, but not quite correct. For example, for the numbers 5, 54, and 56 a lexicographic sort will produce {5, 54, 56} (in increasing order) or {56, 54, 5} (in decreasing order), but what we really want is {56, 5, 54}, since that produces the largest number possible.

    So we want a comparator for two numbers that somehow puts the biggest digits first.

    1. We can do that by comparing individual digits of the two numbers, but we have to be careful when we step off the end of one number if the other number still has remaining digits. There are lots of counters, arithmetic, and edge cases that we have to get right.

    2. A cuter solution (also mentioned by @Sarp Centel) achieves the same result as (1) but with a lot less code. The idea is to compare the concatenation of two numbers with the reverse concatenation of those numbers. All of the cruft that we have to explicitly handle in (1) is handled implicitly.

      For example, to compare 56 and 5, we'd do a regular lexicographic comparison of 565 to 556. Since 565 > 556, we'll say that 56 is "bigger" than 5, and should come first. Similarly, comparing 54 and 5 means we'll test 545 < 554, which tells us that 5 is "bigger" than 54.

    Here's a simple example:

    // C++0x: compile with g++ -std=c++0x 
    #include 
    #include 
    #include 
    #include 
    
    int main() {
      std::vector v = {
        "95", "96", "9", "54", "56", "5", "55", "556", "554", "1", "2", "3"
      };
      std::sort(v.begin(), v.end(),
          [](const std::string &lhs, const std::string &rhs) {
            // reverse the order of comparison to sort in descending order,
            // otherwise we'll get the "big" numbers at the end of the vector
            return rhs+lhs < lhs+rhs;
          });
    
      for (size_t i = 0; i < v.size(); ++i) {
        std::cout << v[i] << ' ';
      }
    }
    

    When run, this code displays:

    9 96 95 56 556 5 55 554 54 3 2 1
    

提交回复
热议问题