从0开始学算法——第十四天(数组与搜索练习)

写在开头的话

学习了今天的基础知识,让我们来做道题来练练手吧。(题目是别的地方扒来的,参考答案是我自己写的,肯定不是最优解,有更好的方法欢迎评论区交流)

题目一------整数二分

第一题参考答案(Python版)

python 复制代码
import sys
import bisect

def main():
    data = sys.stdin.read().split()
    it = iter(data)
    n = int(next(it))
    q = int(next(it))
    A = [int(next(it)) for _ in range(n)]

    out_lines = []
    for _ in range(q):
        t = int(next(it))
        l = int(next(it))
        r = int(next(it))
        x = int(next(it))

        if t == 1:      # 等于 x 的最左边下标
            low = bisect.bisect_left(A, x) + 1   # 全局第一个 >= x 的下标(1‑based)
            pos = max(low, l)
            if pos <= r and A[pos-1] == x:
                out_lines.append(str(pos))
            else:
                out_lines.append("-1")

        elif t == 2:    # 等于 x 的最右边下标
            high = bisect.bisect_right(A, x) + 1  # 全局第一个 > x 的下标(1‑based)
            pos = min(high-1, r)
            if pos >= l and A[pos-1] == x:
                out_lines.append(str(pos))
            else:
                out_lines.append("-1")

        elif t == 3:    # 第一个 >= x 的下标
            low = bisect.bisect_left(A, x) + 1
            pos = max(low, l)
            if pos <= r:
                out_lines.append(str(pos))
            else:
                out_lines.append("-1")

        else:           # t == 4,第一个 > x 的下标
            high = bisect.bisect_right(A, x) + 1
            pos = max(high, l)
            if pos <= r:
                out_lines.append(str(pos))
            else:
                out_lines.append("-1")

    sys.stdout.write("\n".join(out_lines))

if __name__ == "__main__":
    main()
相关推荐
进击的荆棘20 小时前
递归、搜索与回溯——递归
算法·leetcode·递归
2301_8227032021 小时前
鸿蒙Flutter第三方库FlutterUnit组件百科适配——具体示例还原演示1
算法·flutter·华为·harmonyos·鸿蒙
2301_764441331 天前
LISA时空跃迁分析,地理时空分析
数据结构·python·算法
东北洗浴王子讲AI1 天前
GPT-5.4辅助算法设计与优化:从理论到实践的系统方法
人工智能·gpt·算法·chatgpt
北顾笙9801 天前
LLM学习-day02
学习
Billlly1 天前
ABC 453 个人题解
算法·题解·atcoder
玉树临风ives1 天前
atcoder ABC 452 题解
数据结构·算法
大连好光景1 天前
PYG从入门到放弃
笔记·学习
feifeigo1231 天前
基于马尔可夫随机场模型的SAR图像变化检测源码实现
算法
fengfuyao9851 天前
基于STM32的4轴步进电机加减速控制工程源码(梯形加减速算法)
网络·stm32·算法