Redian新闻
>
An interview question (Detect cycles in a sequence of numbers)
avatar
An interview question (Detect cycles in a sequence of numbers)# JobHunting - 待字闺中
c*5
1
Detecting Cycles
Description:
Given a sequence, write a program to detect cycles within it.
Input sample:
A file containing a sequence of numbers (space delimited). The file can have
multiple such lines. e.g
2 0 6 3 1 6 3 1 6 3 1
Ensure to account for numbers that have more than one digit eg. 12. If there
is no sequence, ignore that line.
Output sample:
Print to stdout the first sequence you find in each line. Ensure that there
are no trailing empty spaces on each line you print. e.g.
6 3 1
Any good idea?
Thanks a lot.
avatar
j*y
5
如果 cycle 里面没有相同的数,可以反过来走
但是对于 2 2 2 3 2 2 2 3 2 2 2 3 这种的还是不行

【在 p*****p 的大作中提到】
: could be wrong:
: 2 0 6 3 1 6 3 5
: has a cycle or not?

avatar
A*u
6
太犀利了
那你有什么好办法

【在 j*****y 的大作中提到】
: 好像不太一样
: 2 2 2 0 6 3 1 6 3 1 6 3 1 就不能用 龟兔赛跑 弄出来

avatar
b*e
7
Using a stack?
push element one by one the the q. Use an hash to record whether a number
has been pushed into the stack or not. Once find an element has been in the
stack. pop out the elements into the arr until the same element is pop out.
Save all poped out eleements in a arry a, say a.size() == n.
Continue scan the element, if next element does not equal to a[0], clean up
a.
if next element == a[0], continue go to next elemenet to see whether it is
equal to a[1], until .....
avatar
b*e
8
Using a stack?
push element one by one the the q. Use an hash to record whether a number
has been pushed into the stack or not. Once find an element has been in the
stack. pop out the elements into the arr until the same element is pop out.
Save all poped out eleements in a arry a, say a.size() == n.
Continue scan the element, if next element does not equal to a[0], clean up
a.
if next element == a[0], continue go to next elemenet to see whether it is
equal to a[1], until .....
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。