腾讯笔试经验-不是大牛-勿看 - Go语言中文社区

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


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;
}

 

 

 

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_19643241/article/details/82728874
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-03-07 16:41:09
  • 阅读 ( 1405 )
  • 分类:职场

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢