📌  相关文章
📜  C ++程序在数组中查找最接近的数字

📅  最后修改于: 2022-05-13 01:55:39.598000             🧑  作者: Mango

C ++程序在数组中查找最接近的数字

给定一个有序整数数组。我们需要找到最接近给定数字的值。数组可能包含重复值和负数。

例子:

Input : arr[] = {1, 2, 4, 5, 6, 6, 8, 9}
             Target number = 11
Output : 9
9 is closest to 11 in given array

Input :arr[] = {2, 5, 6, 7, 8, 8, 9}; 
       Target number = 4
Output : 5

一个简单的解决方案是遍历给定的数组并跟踪当前元素与每个元素的绝对差异。最后返回具有最小绝对差的元素。

一个有效的解决方案是使用二分搜索。

C++
// CPP program to find element
// closest to given target.
#include 
using namespace std;
 
int getClosest(int, int, int);
 
// Returns element closest to target in arr[]
int findClosest(int arr[], int n, int target)
{
    // Corner cases
    if (target <= arr[0])
        return arr[0];
    if (target >= arr[n - 1])
        return arr[n - 1];
 
    // Doing binary search
    int i = 0, j = n, mid = 0;
    while (i < j) {
        mid = (i + j) / 2;
 
        if (arr[mid] == target)
            return arr[mid];
 
        /* If target is less than array element,
            then search in left */
        if (target < arr[mid]) {
 
            // If target is greater than previous
            // to mid, return closest of two
            if (mid > 0 && target > arr[mid - 1])
                return getClosest(arr[mid - 1],
                                  arr[mid], target);
 
            /* Repeat for left half */
            j = mid;
        }
 
        // If target is greater than mid
        else {
            if (mid < n - 1 && target < arr[mid + 1])
                return getClosest(arr[mid],
                                  arr[mid + 1], target);
            // update i
            i = mid + 1;
        }
    }
 
    // Only single element left after search
    return arr[mid];
}
 
// Method to compare which one is the more close.
// We find the closest by taking the difference
// between the target and both values. It assumes
// that val2 is greater than val1 and target lies
// between these two.
int getClosest(int val1, int val2,
               int target)
{
    if (target - val1 >= val2 - target)
        return val2;
    else
        return val1;
}
 
// Driver code
int main()
{
    int arr[] = { 1, 2, 4, 5, 6, 6, 8, 9 };
    int n = sizeof(arr) / sizeof(arr[0]);
    int target = 11;
    cout << (findClosest(arr, n, target));
}
 
// This code is contributed by Smitha Dinesh Semwal


输出:

9

有关详细信息,请参阅有关在数组中查找最接近的数字的完整文章!