给定一个大小为N的数组 arr[] ,任务是为每个数组元素找到数组中存在于其左侧的最近的不等值。如果没有找到这样的元素,则打印-1
例子:
Input: arr[] = { 2, 1, 5, 8, 3 }
Output: -1 2 2 5 2
Explanation:
[2], it is the only number in this prefix. Hence, answer is -1.
[2, 1], the closest number to 1 is 2
[2, 1, 5], the closest number to 5 is 2
[2, 1, 5, 8], the closest number to 8 is 5
[2, 1, 5, 8, 3], the closest number to 3 is 2
Input: arr[] = {3, 3, 2, 4, 6, 5, 5, 1}
Output: -1 -1 3 3 4 4 4 2
Explanation:
[3], it is the only number in this prefix. Hence, answer is -1.
[3, 3], it is the only number in this prefix. Hence, answer is -1
[3, 3, 2], the closest number to 2 is 3
[3, 3, 2, 4], the closest number to 4 is 3
[3, 3, 2, 4, 6], the closest number to 6 is 4
[3, 3, 2, 4, 6, 5], the closest number to 5 is 4
[3, 3, 2, 4, 6, 5, 5], the closest number to 5 is 4
[3, 3, 2, 4, 6, 5, 5, 1], the closest number to 1 is 2
朴素的方法:最简单的想法是遍历给定的数组,对于每个第i个元素,在索引i的左侧找到不等于arr[i]的最近元素。
时间复杂度: O(N^2)
辅助空间: O(1)
有效的方法:
这个想法是将给定数组的元素插入到一个 Set 中,这样插入的数字会被排序,然后对于一个整数,找到它的位置并将它的下一个值与前一个值进行比较,然后打印出两者中更接近的值。
请按照以下步骤解决问题:
- 初始化一组整数S以按排序顺序存储元素。
- 使用变量i遍历数组arr[] 。
- 现在,找到比 arr[i]更小和更大的最近值,分别说 X和Y。
- 如果找不到 X ,则打印Y。
- 如果找不到 Y ,则打印Z。
- 如果找不到 X和Y ,则打印“-1” 。
- 之后,如果abs(X – arr[i])小于abs(Y – arr[i]) ,则将 arr[i]添加到 Set S并打印X。否则,打印Y 。
- 对每个元素重复上述步骤。
下面是上述方法的实现:
C++14
// C++ program for the above approach
#include
using namespace std;
// Function to find the closest number on
// the left side of x
void printClosest(set& streamNumbers, int x)
{
// Insert the value in set and store
// its position
auto it = streamNumbers.insert(x).first;
// If x is the smallest element in set
if (it == streamNumbers.begin())
{
// If count of elements in the set
// equal to 1
if (next(it) == streamNumbers.end())
{
cout << "-1 ";
return;
}
// Otherwise, print its
// immediate greater element
int rightVal = *next(it);
cout << rightVal << " ";
return;
}
// Store its immediate smaller element
int leftVal = *prev(it);
// If immediate greater element does not
// exists print it's immediate
// smaller element
if (next(it) == streamNumbers.end()) {
cout << leftVal << " ";
return;
}
// Store the immediate
// greater element
int rightVal = *next(it);
// Print the closest number
if (x - leftVal <= rightVal - x)
cout << leftVal << " ";
else
cout << rightVal << " ";
}
// Driver Code
int main()
{
// Given array
vector arr = { 3, 3, 2, 4, 6, 5, 5, 1 };
// Initialize set
set streamNumbers;
// Print Answer
for (int i = 0; i < arr.size(); i++) {
// Function Call
printClosest(streamNumbers, arr[i]);
}
return 0;
}
-1 -1 3 3 4 4 4 2
时间复杂度: O(N * log(N))
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。