腾讯 百度 面试题

腾讯:

try

finally

百度:

int array[] = {0,1,2,3,4,5,6,7,8,9...};

随机输出array中的值,并且不能重复,又完整输出一遍

要求空间复杂度和时间复杂度最小

 

http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle

 

Modern method

We'll now do the same thing using Durstenfeld's version of the algorithm: this time, instead of striking out the chosen numbers and copying them elsewhere, we'll swap them with the last number not yet chosen. We'll start by writing out the numbers from 1 to 8 as before. For clarity, we'll use a vertical bar (|) to separate the part of the list that has already been processed from the part that hasn't been permuted yet; of course, no such separator is actually used in the real algorithm:

RangeRollScratch | Result
  1 2 3 4 5 6 7 8 |

For our first roll, we roll a random number from 1 to 8: this time it's 6, so we swap the 6th and 8th numbers in the list:

RangeRollScratch | Result
1–861 2 3 4 5 8 7 | 6

The next random number we roll from 1 to 7, and turns out to be 2. Thus, we swap the 2nd and 7th numbers and move on:

RangeRollScratch | Result
1–727 3 4 5 8 | 2 6

The next random number we roll is from 1 to 6, and just happens to be 6, which means we leave the 6th number in the list (which, after the swap above, is now number 8) in place and just move to the next step. Again, we proceed the same way until the permutation is complete:

RangeRollScratch | Result
1–661 7 3 4 5 | 8 2 6
1–515 7 3 4 | 1 8 2 6
1–435 7 4 | 3 1 8 2 6
1–335 7 | 4 3 1 8 2 6
1–217 | 5 4 3 1 8 2 6

At this point there's nothing more that can be done, so the resulting permutation is 7 5 4 3 1 8 2 6.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值