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

本文探讨了在有限内存环境下,通过使用快慢指针法解决循环调用函数产生的环形序列问题,包括计算环长、循环起点及避免冗余存储的方法。
//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)空间找到长度了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值