检查随机数列表是否包含 1 到 n 范围的有效方法
如果我有一个随机打乱的数组,其中包含数字 1 到 n,那么找到该数组包含范围 1 到 n(无重复)的好方法是什么?例如,
n = 6; [1, 3, 6, 2, 4, 5] => true
n = 6; [1, 1, 2, 4, 5, 6] => false
If I have an randomly shuffled array with the numbers 1 to n, what is a good way to find that the array contains the range 1 to n (no repeats)? For example,
n = 6; [1, 3, 6, 2, 4, 5] => true
n = 6; [1, 1, 2, 4, 5, 6] => false
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
听起来像家庭作业,但是......
使用 Set 非常简单:
Sounds suspiciously like homework, but...
This is very simple using a Set:
创建一个大小为 n 的数组,遍历数组并以此作为索引递增数组中的位置。如果任何时候 counts 数组具有非 0 或非 1 值,您可以停止。如果找不到索引,您可以立即停止,因为您知道自己没有它。
这是一个简单的 Java 示例。在此示例中,您不需要在最后进行计数,因为任何会导致非 1 值的情况都会在中间导致失败。
Make an array of size n, pass through your array and increment the position in the array with that as an index. If at any time the counts array has non 0 or non 1 value, you can stop. If you can't find the index, you can stop now since you know you don't have it.
Here's a quick Java example. In this example, you do not need to count at the end because anything that would cause a non-1 value would cause a failure during the middle.
使用高斯公式预先计算最终总和:
对已打乱的列表进行线性循环,将数字相加,如果运行总和与最终总和相同,则返回 true。
Use the Gauss formula to precompute what the final sum will be:
Do a linear loop over your shuffled list, adding the numbers as you go, and if your running sum is the same as your final sum, return true.
您需要对数组进行排序。以下是一些流行选择的链接,http://en.wikipedia.org/wiki/Sorting_algorithm。就我个人而言,我建议冒泡排序作为简单的解决方案,并推荐合并排序作为更难、更快的版本。
列表排序后,您可以通过迭代数组并确保下一个 # 大于前一个来检查重复。此外,还可以将其添加到排序中以缩短计算时间。
最后,检查第一个和最后一个数字,确保它们等于 1 和 n。
You're going to want to sort the array. Here is a link to some popular choices, http://en.wikipedia.org/wiki/Sorting_algorithm. Personally I recommend bubble sort for a simple solution, and merge sort for a harder, faster version.
Once the list is sorted, you can check for repeats by iterating through the array and making sure that the next # is greater than the previous. Also, this can be added to the sort to shorten computing time.
Finally, check the first and last numbers to make sure they equal 1 and n.
如果不允许有额外的空间(面试问题中的典型约束),那么您可以先对数组进行排序,然后从左到右顺序扫描排序后的数组,看看每个元素是否都比前一个元素大1。时间复杂度为O(n*logn)。
If extra space is not allowed(typical constraint in an interview question), then you can sort the array first and scan the sorted array sequentially from left to right to see if every element is larger than its previous element by 1. The time complexity is O(n*logn).