首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >腾讯云算法面试题-给定边界输出对应索引下标

腾讯云算法面试题-给定边界输出对应索引下标

作者头像
Lvshen
发布2022-05-05 15:54:04
发布2022-05-05 15:54:04
3590
举报
题目
代码语言:javascript
复制
给出有序数组(非递减)和闭区间, 找出数组中在区间之内的元素起始位置和结束位置
* 输入:
* 1. 有序数组[1,1,2,3,4,5,5]
* 2. 闭区间[-3,3]
* 输出:[0,3]
* 解释:在数组中,前4个元素在区间之内,则起始位置为0,结束位置为3
* 要求:最坏情况时间复杂度小于O(n)
代码
代码语言:javascript
复制
public class TxTest {

    public static void main(String[] args) {
        int[] arrays = {-10, 1, 2, 3, 4, 5, 5};
        fun1(arrays, -3, 3);
    }

    public static void fun1(int[] arrays, int start, int end) {
        int startIndex = startBound(arrays, start);
        int endIndex = endBound(arrays, end);
        System.out.println("[" + startIndex + "," + endIndex + "]");
    }

    private static int startBound(int[] arrays, int key) {
        int start = 0;
        int last = arrays.length;
        while (start < last) {
            int mid = (start + last) / 2;
            if (arrays[mid] >= key) {
                last = mid;
            } else {
                start = mid + 1;
            }
        }
        return start;
    }

    private static int endBound(int[] arrays, int key) {
        int start = 0;
        int last = arrays.length;
        while (start < last) {
            int mid = (start + last) / 2;
            if (arrays[mid] <= key) {
                start = mid + 1;
            } else {
                last = mid;
            }
        }
        return start - 1;
    
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-07-13,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Lvshen的技术小屋 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目
  • 代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档