排列給定的數字以形成最大的數字?


此處我們將瞭解如何透過重新排列給定的數字來生成最大的數字。假設給定了{45、74、23},該程式將找到最大數字,即 744523。所以每個數字將不會被單獨排列,而是整個數字將被放置在最大數字的位置。

為了解決此問題,我們將使用字串排序。但比較邏輯是不同的。比較函式將使用兩個數字 a 和 b,然後將它們連線起來形成 ab 和 ba。其中哪個更大,則認為是那個。

演算法

比較字串 (a, b)

begin
   ab := concatenate b with a
   ba := concatenate a with b
   compare ba with ab, then return 1 if ba is bigger, otherwise return 0
end
getLargest(arr):
begin
   sort the arr with the comparison logic using compareString()
   for each string s in arr, do
      print s
   done
end

示例

 動態演示

#include<iostream>
#include <string>
#include &t;vector>
#include <algorithm>
using namespace std;
int stringCompare(string a, string b) {
   string ab = a.append(b);
   string ba = b.append(a);
   return ab.compare(ba) > 0 ? 1: 0;
}
void getLargest(vector<string> arr) {
   sort(arr.begin(), arr.end(), stringCompare); //sort the array
   for (int i =0; i < arr.size() ; i++ )
      cout << arr[i];
}
int main() {
   vector<string> arr;
   arr.push_back("45");
   arr.push_back("74");
   arr.push_back("23");
   getLargest(arr);
}

輸出

744523

更新於: 2019 年 7 月 30 日

207 次瀏覽

開啟你的 職業

完成課程獲得認證

獲取開始
廣告
© . All rights reserved.