📌  相关文章
📜  查找数组中每个元素的最接近值

📅  最后修改于: 2021-04-28 14:00:47             🧑  作者: Mango

给定整数数组,为每个元素找到最接近的元素。

例子:

一个简单的解决方案是运行两个嵌套循环。我们一个接一个地选择一个外部元素。对于每个拾取的元素,我们遍历剩余的数组并找到最接近的元素。该解决方案的时间复杂度为O(n * n)

一个有效的解决方案是使用自我平衡BST(按照C++中的设置和Java的TreeSet的实现)。在自平衡BST中,我们可以在O(Log n)时间执行插入操作和最接近的较大操作。

// Java program to demonstrate insertions in TreeSet
import java.util.*;
  
class TreeSetDemo {
    public static void closestGreater(int[] arr)
    {
        if (arr.length == -1) {
            System.out.print(-1 + " ");
            return;
        }
  
        // Insert all array elements into a TreeMap.
        // A TreeMap value indicates whether an element
        // appears once or more.
        TreeMap tm = 
                    new TreeMap();
        for (int i = 0; i < arr.length; i++) {
  
            // A value "True" means that the key
            // appears more than once.
            if (tm.containsKey(arr[i]))
                tm.put(arr[i], true);
            else
                tm.put(arr[i], false);
        }
  
        // Find smallest greater element for every
        // array element
        for (int i = 0; i < arr.length; i++) {
  
            // If there are multiple occurrences
            if (tm.get(arr[i]) == true)
            {
                System.out.print(arr[i] + " ");
                continue;
            }
  
            // If element appears only once
            Integer greater = tm.higherKey(arr[i]);
            Integer lower = tm.lowerKey(arr[i]);
            if (greater == null)
                System.out.print(lower + " ");
            else if (lower == null)
                System.out.print(greater + " ");
            else {
                int d1 = greater - arr[i];
                int d2 = arr[i] - lower;
                if (d1 > d2)
                    System.out.print(lower + " ");
                else
                    System.out.print(greater + " ");
            }
        }
    }
  
    public static void main(String[] args)
    {
        int[] arr = { 10, 5, 11, 6, 20, 12, 10 };
        closestGreater(arr);
    }
}
输出:
10 6 12 5 12 11 10

练习:另一个有效的解决方案是使用也可以在O(n Log n)时间内工作的排序。编写完整的算法和代码以用于基于排序的解决方案。