跳到正文

个人记录

一种O(log n)的数组查找最大值

Dennis_J约 1 分钟
原文
文章信息与版本

文章信息

发布
2025年9月27日
收录
2025年12月12日
更新
2026年11月5日
篇幅
约 1 分钟

版本

  1. v2当前
  2. v1

一些实用的小妙招

1.一种O(log n)的数组查找最大值

通用的查找最大值为定义maxnmaxn为极小值,并为遍历数组时令maxn=max⁡(maxn,ai)maxn=\max(maxn,a_i);
回顾我们所学知识,我们发现二分也可用于查找,其时间复杂度为O(log⁡n)O(\log{n});

我们可以将数组预处理为有序数组,然后进行二分查找;
时间复杂度O(log⁡n)O(\log{n}),不过预处理时间复杂度较大;

代码:

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
int a[114514]; 
signed main()
{
    int n;
    cin>>n;
    for(int i=1;i<=n;i++)
    {
    	cin>>a[i];
	}
	sort(a+1,a+n+1);
	cout<<a[lower_bound(a+1,a+n+1,a[n])-a];
    return 0;
}

2.O((n+q)log n) 静态区间异或和

这里

原文