在正常的數字系統中,0是最小的數字,而9是最大的數字。在這個問題中,我們將得到一個長度為10的列表,從索引0到索引9表示一個數字,它表示該數字的優先級,列表將按照遞增順序排列,這意味著出現在最後索引的數字具有最高的優先權。我們還將得到一個數字,我們需要找到比當前數字稍大的下一個數字。
Input 1: Given number = “123” Given array = { 9, 2, 3, 6, 8, 1, 0, 5, 4, 7} Output: 132
從給定的優先權數組中,我們可以看到1的優先權大於2和3。與2相比,3的優先權更高。因此,如果給定數字的下一個排列將透過交換2和3來實現。
Input 2: Given number = 132 Given array = { 9, 2, 3, 6, 8, 1, 0, 5, 4, 7} Output: 132
From the given priority array, we can see that the priority of 1 is greater than both 2 and 3. Priority of 3 is greater as compared to of 2. So, there will be no next permutation available.
方法#include <bits/stdc++.h> using namespace std; // priority array or array in which the priority of each digit will be stored int prio[10]; // defining the compare function bool compare(char& a, char& b){ return prio[a-'0'] < prio[b-'0']; } // function to get the next permuatation int nextNum(int n, int arr[]){ for(int i=0; i<10; i++){ prio[arr[i]] = i; } // converting the given number into string string str = to_string(n); // calling the next permuatation stl function for the given string we will compare by custom function bool cur = next_permutation(str.begin(),str.end(),compare); if(cur == false){ // indicating the next permutation does not exist return n; } n = stoi(str); // converting string back to number return n; } int main(){ int n = 312; // the given number int arr[] = {9, 2, 3, 6, 8, 1, 0, 5, 4, 7}; // given array cout<<"The next number or permutation for the given number is: "<<nextNum(n, arr); return 0; }
The next number or permutation for the given number is: 123
The space complexity of the above code is O(N) because we are creating a new string to use the next permutation function.
Note: If the current number is the greater number among all the permutations then the next permutation function will return false and we will return the same number as the next permutation does not exist.#does not#結論
以上是根據數字的優先級,翻譯如下:基於數位優先級的下一個較大的數字的詳細內容。更多資訊請關注PHP中文網其他相關文章!