📌  相关文章
📜  查找每个数组元素左侧存在的最接近的值

📅  最后修改于: 2021-05-18 01:22:30             🧑  作者: Mango

给定大小为N的数组arr [] ,每个数组元素的任务是找到数组左端存在的最接近的不等值。如果找不到这样的元素,则打印-1

例子:

天真的方法:最简单的想法是遍历给定的数组,对于每个i个元素,在索引i的左侧找到不等于arr [i]的最近元素。
时间复杂度: O(N ^ 2)
辅助空间: O(1)

高效方法:

想法是将给定数组的元素插入Set中,以便对插入的数字进行排序,然后对一个整数进行查找,找到其位置并将下一个值与前一个值进行比较,然后从两个值中打印出更接近的值。
执行以下步骤解决该问题:

  • 初始化一组整数S ,以按排序顺序存储元素。
  • 使用变量i遍历数组arr []
  • 现在,找到小于和大于arr [i]的最近值,分别说XY。
    • 如果找不到X ,则打印Y。
    • 如果找不到Y ,则打印Z。
    • 如果找不到XY ,则打印“ -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)