找到下一个更大的数字,每个 Array 元素恰好有两个唯一数字
给定一个具有N个整数的数组arr[] ,任务是找到下一个更大的数字X ,即X >= arr[i]对于范围[0, N)中的每个i ,使得X中唯一数字的计数为正好2 。
例子:
Input: arr[] = {123, 234}
Output: 131 242
Explanation: For the given array, 131 is the smallest number greater that 123 having exactly 2 unique digits. Similarly, 242 is the smallest number greater that 234 having exactly 2 unique digits.
Input: arr[] = {35466666}
Output: 35533333
朴素方法:给定的问题可以通过迭代所有大于arr[i]的整数来解决[0, N)范围内的每个i并跟踪第一个整数,使得整数中唯一数字的计数为正好2。
时间复杂度: O(N * M),其中 M 表示 arr[] 中的最大元素。
辅助空间: O(log N)
高效方法:上述方法可以使用位掩码进行优化。可以看出,在给定范围内具有两位数字的所有整数都可以通过迭代所有可能的两位唯一数字对并生成所有可以从它们形成的数字来计算。可以通过本文讨论的算法来完成。之后,可以使用集合数据结构来存储所有整数,对于arr[i]的每个值,可以使用二分查找的 lower_bound函数找到大于arr[i]的最小整数。
下面是上述方法的实现:
C++
// C++ program of the above approach
#include
using namespace std;
#define int long long
// Stores the set of integers with 2 unique digits
set helper;
vector nums;
// Function to find the value of a^b
int power(int a, int b)
{
// Stores the value
int ans = 1;
while (b > 0) {
if (b & 1) {
ans = ans * a;
}
b = b >> 1;
a = a * a;
}
// Return Answer
return ans;
}
void nextGreaterEle(int arr[], int N)
{
// Loop to iterate the given array
for (int i = 0; i < N; i++) {
// For each array element, find next
// greater element in the vector nums
// of integers using lower_bound
cout << *lower_bound(nums.begin(), nums.end(),
arr[i])
<< " ";
}
}
// Function to calculate the digits having
// exactly two unique digits
void preProcess()
{
// Loop to iterate over all possible
// pairs of digits from 0 to 9
for (int i = 0; i <= 9; i++) {
for (int j = 0; j <= 9; j++) {
// Stores the maximum length of integer
int len = 10;
for (int k = 0; k <= (1 << len); k++) {
int temp = k;
int number = 0;
int curLen = 0;
while (temp > 0) {
if (temp & 1) {
// Include numbers with the
// next digit as i
number = i * power(10, curLen)
+ number;
}
else {
// Include numbers with the next
// next digit as j
number = j * power(10, curLen)
+ number;
}
// Update temp
temp = (temp >> 1);
curLen++;
}
// Insert the current number into the set
helper.insert(number);
while (curLen <= len) {
number = j * power(10, curLen) + number;
helper.insert(number);
curLen++;
}
}
}
}
// Loop to insert all the integers into
// a vector from the set if the unique digits
// in the integer is exactly two.
for (auto cur : helper) {
// Stores the unique digits
set count;
int orz = cur;
while (cur > 0) {
count.insert(cur % 10);
cur = cur / 10;
}
// If count of exactly two
if (count.size() == 2) {
nums.push_back(orz);
}
}
}
// Driver Code
signed main()
{
int arr[] = { 123, 234 };
int N = sizeof(arr) / sizeof(arr[0]);
preProcess();
nextGreaterEle(arr, N);
return 0;
}
131 242
时间复杂度: O(10 6 + N * log N) = O(N * log N)
辅助空间: O(10 6 ) = O(1)