二分查找c++

题目1-数的三次方

#include<iostream>
float n;
using namespace std;
double q(double a){return a*a*a;}
int main()
{
    cin >> n;
     double l=-10000,r=10000;
    
    while(r-l>=1e-7)
    {
        double mid=(l+r)/2;
        if(q(mid)>=n) r=mid;
        else
        {
            l=mid;
        }
    }
    
    printf("%.6f",l);
}

数据类型如果定义为float,就会超时!!!很神奇

题目2-最短的不重复出现字串字串

输入一个字符串长度n和一个长度为n的字符串,输出一个长度,长度是最短的窗口使其不重复出现同样的字串如a="sdsd",则输出3,长度为2会找到重复的字串,b="ascd",输出1,字符串使用了哈希储存,最短长度使用了二分算法。

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
string s;
int n;
unordered_set<string> Hash;
bool check(int m)
{
	for (int i = 0; i + m <= n; i++)
	{
		string v;
		v = s.substr(i, m);
		if (Hash.count(v)) return false;
		Hash.insert(v);
	}
	return true;
}
int main()
{
	cin >> n >> s;
	int l = 1, r = n;
	while (r > l)
	{
		int mid = (l + r) / 2;
		if (check(mid)) r = mid;
		else
		{
			l = mid + 1;
		}
	}
	cout << r;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

@nullptr

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值