谷歌面试题之求一个满足要求的数组

时间:2014.05.14

地点:基地

心情:连续好几天没写博客了,这几天一直都练车,晚上回来都还累的,后悔当初过于紧张和追求完美,结果一下子挂了~所幸是这次过了,完美的一百分哇

--------------------------------------------------------------------------------

一、题目

  正整数序列Q中的每个元素都至少能被正整数a和b中的一个整除,现给定a和b,需要计算出Q中的前几项,例如,当a=3,b=5,N=6时,序列为3,5,6,9,10,12
(1)、设计一个函数void generate(int a,int b,int N ,int * Q)计算Q的前几项

(2)、设计测试数据来验证函数程序在各种输入下的正确性

--------------------------------------------------------------------------------

二、分析

无非是按顺序求出a和b的倍数,于是可相继在a和b的基础上累加,通过比较大小按顺序追加到数组,并向下一个可能数据滑动,这样的时间复杂度为O(n)

三、源码

#include<iostream>
#include<cassert>
using namespace std;
void Generate(int a, int b, int N, int* Q)
{
	//Precondition: Parameter a,b and N are positive integer
	//Postcondition: Caculate the front N items which every item%a==0 or item%b==0
	//               and then added to the array Q 
	assert((a > 0) && (b > 0) && (N > 0));
	int current_a = a, current_b = b;
	for (int count = 0; count < N; ++count)
	{
		if (current_a < current_b)
		{
			Q[count] = current_a;
			current_a += a;
		}
		else if (current_b < current_a)
		{
			Q[count] = current_b;
			current_b+=b;
		}
		else
		{
			Q[count] = current_a;
			current_a += a;
			current_b += b;
		}
	}
}
int main()
{
	size_t a, b, N;
	cout << "Please input a b and N" << endl;
	cin >> a >> b >> N;
	int* p_arr = new int[N];
	Generate(a, b, N, p_arr);
	cout << "The result are as fllows: " << endl;
	for (size_t i = 0; i < N; ++i)
		cout << p_arr[i] << " ";
	cout << endl;
	delete p_arr;
	p_arr = nullptr;
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值