Find a number in the array having least difference with the given number (n)

Problem
/* Facebook
 * Given - a number (n) and a sorted array 
 * Find a number in the array having least difference with the given number (n).
 * */

From site:  https://sites.google.com/site/spaceofjameschen/home

/*
============================================================================
Author         : James Chen
Email          : [email protected]
Description    : Find a number in the array having least difference with the given number (n)
Created Date   : 08-07-2013 
Last Modified  :
============================================================================
*/

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>

using namespace std;

int FindNearestNum(int* arr, int len, int n)
{
    if(len == 1) return arr[0];
    if(n < arr[0]) return arr[0];
    if(n > arr[len - 1]) return arr[len - 1];

    int low = 0;
    int up = len - 1;

    while(low <= up){
        int mid = low + (up - low) / 2;

        if(arr[mid] == n){
            return n;
        }
        else if(arr[mid] > n){
            up = mid - 1;
        }
        else{
            low = mid + 1;
        }
    }

    return abs(arr[low] - n) > abs(arr[up] - n) ? arr[up] : arr[low];
}

void DoTest(int* arr, int len, int n)
{
    cout << "The array is: " << endl;
    for(int i = 0; i < len; ++i){
        cout << setw(3) << arr[i];
    }
    cout << endl;

    cout << "The number to find is: " << n << endl;

    int foundNum = FindNearestNum(arr, len, n);

    cout << "The nearest num is: " << foundNum << endl;

    auto expectedNum = min_element(arr, arr + len, [=](int i, int j) -> bool{
        return abs(n - i) < abs(n - j);
    });

    cout << "The expected num is: " << *expectedNum << endl;
    cout << "---------------------------------------" << endl;
}

int main(int argc, char* argv[])
{
    int arr[] = { -1, 0, 2, 3, 4, 8, 9, 20, 29, 43, 44, 45, 46, 47, 48, 49 };

    for (int i = -3; i < 50; i ++){
        DoTest(arr, sizeof(arr)/sizeof(arr[0]), i);
    }
    
    int arr1[] = { -2 };
    for (int i = -3; i < 5; i += 3){
        DoTest(arr1, sizeof(arr1)/sizeof(arr1[0]), i);
    }

    int arr2[] = { -2, 7 };
    for (int i = -3; i < 5; i += 3){
        DoTest(arr2, sizeof(arr2)/sizeof(int), i);
    }

    int arr3[] = { -2, 7, 100 };
    for (int i = -3; i < 5; i += 3) {
        DoTest(arr3, sizeof(arr3)/sizeof(int), i);
    }
    return 0;
}


你可能感兴趣的:(Find a number in the array having least difference with the given number (n))