使用 C++ 在无序数组中查找 floor 和 ceil。


这里我们将介绍如何在一个无序数组中查找 floor 和 ceiling。floor 值为小于或等于 x 的较大元素,而 ceiling 值为大于 x 的最小元素。如果数组 A = [5, 6, 8, 9, 6, 5, 5, 6],并且 x 是 7,则 floor 值为 6,ceiling 值为 8。

为了解决这个问题,我们将采用线性搜索方法。我们将遍历数组并针对 x 跟踪两个距离。

  • 大于或等于 x 的元素的最小距离
  • 小于或等于 x 的元素的最小距离
  • 最后,打印具有最小距离的元素

示例

#include<iostream>
using namespace std;
void floorCeilingPair(int arr[], int n, int x) {
   int floor_index, ceiling_index;
   int floor_dist = INT_MAX, ceil_dist = INT_MAX;
   for (int i=0; i<n; i++) {
      if (arr[i] >= x && ceil_dist > (arr[i] - x)) {
         ceiling_index = i;
         ceil_dist = arr[i] - x;
      }
      if (arr[i] <= x && floor_dist > (x - arr[i])) {
            floor_index = i;
            floor_dist = x - arr[i];
      }
   }
   if (floor_dist == INT_MAX)
      cout << "Floor not found" << endl;
   else
      cout << "Floor value is " << arr[floor_index] << endl;
   if (ceil_dist == INT_MAX)
      cout << "Ceiling not found" << endl;
   else
      cout << "Ceil value is " << arr[ceiling_index] << endl;
}
int main() {
   int arr[] = {5, 6, 8, 9, 6, 5, 5, 6};
   int n = sizeof(arr)/sizeof(int);
   int x = 7;
   floorCeilingPair(arr, n, x);
}

输出

Floor value is 6
Ceil value is 8

更新于:2019-10-29

查看次数:542

开启你的 事业

通过完成课程获得认证

开始
广告
© . All rights reserved.