腾讯笔试经验-不是大牛-勿看

2018.9.16

1.字符串系数。字符串A和B,找到B中有A的多少个长度为k的子串。

思路:找到A中长度为k的子串,存到set里。

           找B中的长度为k的子串,若在set里有就++。   

只通过90%。

#include <iostream>
#include <string>
#include <set>
#include <vector>
#include <map>
using namespace std;
int main(){
	int k;
	cin>>k;
	string a,b;
	cin>>a>>b;
	int an = a.size();
	int bn = b.size();
	set<string> aa;
	map<string,int> bb;

	for (int i=0;i<an-k+1;i++)
	{		
		string t = a.substr(i, k);
		aa.insert(t);
		cout << t.c_str()<<endl;
	}
	int res = 0;
	for (int i = 0; i < bn-k+1; i++)
	{
		string t = b.substr(i,k);
		if (aa.count(t))
			res++;
	}
	cout<<res;

	return 0;
}

 

2. 前n个数的和为x+y,求至少需要其中几个数相加得x,剩下的刚好为y。   

.

思路:两个数m和n,首先看x+y是否刚好为前t项和,否则返回-1。

           从1到n中找出等于x的最少需要几个数:

           1.若x<=n  返回1

           2.从后向前计算,若x<=最后两个数的和, 返回2

             。。。。。。。。。。。。。。。。。。

好吧,这是看了别人的思路得到的,我想复杂了,老想找到哪几个数,其实只要求出个数就好了!!!!!哎!没来得及测试的

#include <iostream>
#include <math.h>
using namespace std;
int reachNumber(int x, int y) {
	int res = 0;
	int target = x + y;
	int n = ceil((-1.0 + sqrt(1 + 8.0*target)) / 2);
	int sum = n * (n + 1) / 2;
	if (sum != target){
		res = -1;
		return res;
	}
	int temp = 0;
	for (int i = n; i >= 1; i--){
		temp+=i;
		if (x <= temp){
			return (n + 1 - i);
		}
	}

}

int main(){
	int x, y;
	cin >> x >> y;
	int num = reachNumber(x, y);
	cout << num;
	return 0;
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值