截屏2020-03-28 下午3.15.14.png

演示:

  1. 五个人:围成圈
  2. a,b,c,d,e
  3. 每传到第五次,当前的人淘汰,直到最后一个人了。
  4. a,b,c,d,e => e出去,
  5. a,b,c,d,a=> a出去
  6. b,c,d,b,c => c出去,
  7. d,b,d,b,d=> d出去 => 只剩b了。

用队列思考:

  1. const q = new Queue(["a", "b", "c", "d", "e"]);
  2. let timer = 0;
  3. //第一次淘汰:
  4. while (timer < 5) {
  5. const dequeue = q.dequeue();
  6. timer !== 4 && q.enqueue(dequeue);
  7. timer === 4 && console.log(dequeue,q);
  8. timer++
  9. }
  10. timer = 0;
  11. //第2次淘汰:
  12. while (timer < 5) {
  13. const dequeue = q.dequeue();
  14. timer !== 4 && q.enqueue(dequeue);
  15. timer === 4 && console.log(dequeue,q);
  16. timer++
  17. }
  18. timer = 0;
  19. //第3次淘汰:
  20. while (timer < 5) {
  21. const dequeue = q.dequeue();
  22. timer !== 4 && q.enqueue(dequeue);
  23. timer === 4 && console.log(dequeue,q);
  24. timer++
  25. }
  26. timer = 0;
  27. //第4次淘汰:
  28. while (timer < 5) {
  29. const dequeue = q.dequeue();
  30. timer !== 4 && q.enqueue(dequeue);
  31. timer === 4 && console.log(dequeue,q);
  32. timer++
  33. }
  34. // 1 Queue { lists: [ 2, 3, 6, 7, 8, 9 ] }
  35. // e Queue { lists: [ 'a', 'b', 'c', 'd' ] }
  36. // a Queue { lists: [ 'b', 'c', 'd' ] }
  37. // c Queue { lists: [ 'd', 'b' ] }
  38. // d Queue { lists: [ 'b' ] }

归纳:

  1. function drummingFlowers(arr, loopNum) {
  2. const q = new Queue(arr);
  3. let timer = 1;
  4. while (q.size() > 1) {
  5. const dequeue = q.dequeue();
  6. timer % loopNum !== 0 && q.enqueue(dequeue);
  7. timer++
  8. }
  9. return q.front();
  10. }