📜  根据数字的优先级选择下一个更大的数字

📅  最后修改于: 2021-05-07 18:10:47             🧑  作者: Mango

给定一个包含n个数字的数字num 。问题是,根据给定的数字优先级,使用num中相同的数字集查找下一个更大的数字。例如,数字的优先级为1、6、4、5、2、9、8、0、7、3 这仅表示1 <6 <4 <5 <2 <9 <8 <0 <7 <3 。如果无法形成下一个更大的数字,则打印原始数字。

例子:

Input : num = "231447"
        pre[] = {1, 6, 7, 5, 2, 9, 8, 0, 4, 3}
Output : 237144
According to the precedence of digits 1 is 
being considered as the smallest digit and 3
is being considered as the largest digit.

Input : num = "471"
        pre[] = {1, 6, 7, 5, 2, 9, 8, 0, 4, 3}
Output : 471

方法:以下是步骤:

  1. 创建大小为10的priority []数组。借助优先级数组pre [] ,为priority []中的每个数字分配一个优先级编号,其中“ 1”被认为是最小优先级,而“ 10”被认为是最高优先级。
  2. 结合使用STL C++ next_permutation和手动定义的比较函数,可以找到下一个更大的排列。

// C++ implementation to find the next greater number
// on the basis of precedence of digits
#include 
  
using namespace std;
  
#define DIGITS 10
  
// priority[] to store the priority of digits
// on the basis of pre[] array. Here '1' is being
// considered as the smallest priority as '10' as
// the highest priority
int priority[DIGITS];
  
// comparator function used for finding the
// the next greater permutation
struct compare {
  bool operator()(char x, char y) {
    return priority[x - '0'] < priority[y - '0'];
  }
};
  
// function to find the next greater number
// on the basis of precedence of digits
void nextGreater(char num[], int n, int pre[]) {
  memset(priority, 0, sizeof(priority));
  
  // variable to assgin priorities to digits
  int assign = 1;
  
  // assigning priorities to digits on
  // the basis of pre[]
  for (int i = 0; i < DIGITS; i++) {
    priority[pre[i]] = assign;
    assign++;
  }
  
  // find the next greater permutation of 'num'
  // using the compare() function
  bool a = next_permutation(num, num + n, compare());
  
  // if the next greater permutation does not exists
  // then store the original number back to 'num'
  // using 'pre_permutation'.
  if (a == false)
    prev_permutation(num, num + n, compare());
}
  
// Driver program to test above
int main() {
  char num[] = "231447";
  int n = strlen(num);
  int pre[] = {1, 6, 7, 5, 2, 9, 8, 0, 4, 3};
  nextGreater(num, n, pre);
  cout << "Next Greater: " << num;
  return 0;
}

输出:

Next Greater: 237144

时间复杂度:O(n)。
辅助空间:O(1)。