这道题一上来就用数组的同学会得到一句My grandmother runs faster than your code的评价
因为使用数组的话查询操作时间复杂度是O(N),用上for循环直接O(N^2)了,所以这道题要用Set结构来解,这道题的进阶版就是Google面试题和LeetCode1 两数相加
Q & A:
Q:为什么不用数组
A:Set结构的查询操作比数组include方法的快,且该题不需要返回原数组下标值(用不上Map结构)
Set.prototype.has()时间复杂度为O(1),而数组的include方法和indexOf方法时间复杂度为O(N)
详情参见MDN Set这一章节
Q:为什么不用数组的splice方法进行操作
A:数组的splice方法时间复杂度为O(N),而Set的add方法时间复杂度为O(1)
*/
// 这种方法的时间复杂度为O(N) (即N * 1,N是for循环的时间复杂度)
const arr = ['鹿晗', '王俊凯', '蔡徐坤', '彭于晏', '周杰伦', '刘德华', '赵本山'];
const set = new Set();
while (true) {
if (set.size > 3) break;
const random = Math.trunc(Math.random() * 7);
if (!set.has(arr[random])) set.add(arr[random]);
else set.add(arr[Math.trunc(Math.random() * 7)]);
}
console.log(set.keys());