现在的位置: 首页 > 综合 > 正文

关于函数调用的loop的一个问题

2013年12月10日 ⁄ 综合 ⁄ 共 720字 ⁄ 字号 评论关闭

//Q: Given a function that takes in an integer input and gives out an integer:
//int func(int input);
//This function is deterministic. It always gives the same output value for a given input. Say func(8) = 7 whenever it is called.
//Now this function is called multiple times in a loop. This would generate a stream of integers, what is the length of this loop ? give me the count of how many numbers are repeated and how many 
//numbers are not repeated. He said there is very limited memory: you can store only a certain number of integers at a time, but not all of them.

就是说有一个函数 int func(int input), 给一个输入值,返回一个输出,新的输出会成为下一个的输入。在函数的调用过程中总会进入一个loop,判断对于一个给定的输入值,这样循环调用产生的loop的长度

看起来非常像那个经典的链表找环问题,那题用快慢两个指针,我觉得这题也能用类似的办法。用两个变量,初始a=b=input,每次迭代中a=f(a),b=f(f(b)),如果函数保证总会进loop,那a和b总会相等。就能得到loop长度的一个整倍数,然后能找到loop起点,然后就能O(1)空间找到长度了

抱歉!评论已关闭.