给定大小为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” 。
- 之后,将arr [i]添加到集合S中,如果abs(X – arr [i])小于abs(Y – arr [i]) ,则打印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)