相关疑难解决方法(0)

查找排序数组中第一个大于目标的元素

在一般的二进制搜索中,我们正在寻找出现在数组中的值.但是,有时我们需要找到比目标更大或更小的第一个元素.

这是我丑陋,不完整的解决方案:

// Assume all elements are positive, i.e., greater than zero
int bs (int[] a, int t) {
  int s = 0, e = a.length;
  int firstlarge = 1 << 30;
  int firstlargeindex = -1;
  while (s < e) {
    int m = (s + e) / 2;
    if (a[m] > t) {
      // how can I know a[m] is the first larger than
      if(a[m] < firstlarge) {
        firstlarge = a[m];
        firstlargeindex = m;
      }
      e = m - …
Run Code Online (Sandbox Code Playgroud)

arrays algorithm binary-search

51
推荐指数
3
解决办法
4万
查看次数

标签 统计

algorithm ×1

arrays ×1

binary-search ×1