检查随机数列表是否包含 1 到 n 范围的有效方法

发布于 2024-12-07 09:14:20 字数 168 浏览 0 评论 0原文

如果我有一个随机打乱的数组,其中包含数字 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

枫以 2024-12-14 09:14:20

听起来像家庭作业,但是......

使用 Set 非常简单:

/* Convert to your favorite language */

validateArray(a, n) {
  assertEqual(n, a.length)
  def s = new Set(a); // set with all elements of a
  assertEqual(s, Set(1..n)); // should be equal to set containing 1 to n
}

Sounds suspiciously like homework, but...

This is very simple using a Set:

/* Convert to your favorite language */

validateArray(a, n) {
  assertEqual(n, a.length)
  def s = new Set(a); // set with all elements of a
  assertEqual(s, Set(1..n)); // should be equal to set containing 1 to n
}
染柒℉ 2024-12-14 09:14:20

创建一个大小为 n 的数组,遍历数组并以此作为索引递增数组中的位置。如果任何时候 counts 数组具有非 0 或非 1 值,您可以停止。如果找不到索引,您可以立即停止,因为您知道自己没有它。

这是一个简单的 Java 示例。在此示例中,您不需要在最后进行计数,因为任何会导致非 1 值的情况都会在中间导致失败。

boolean isRange(int[] arr) {

    int[] counts = new int[arr.length];

    for(int i : arr) {
        if(i < 1 || i > arr.length) return false;
        if(counts[i - 1] != 0) return false;
        counts[i-1] = 1;
    }
    return true; // if it wasn't, we would have failed by now

}

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.

boolean isRange(int[] arr) {

    int[] counts = new int[arr.length];

    for(int i : arr) {
        if(i < 1 || i > arr.length) return false;
        if(counts[i - 1] != 0) return false;
        counts[i-1] = 1;
    }
    return true; // if it wasn't, we would have failed by now

}
哆兒滾 2024-12-14 09:14:20

使用高斯公式预先计算最终总和:

final_sum = k * (k+1)
            ---------
                2

对已打乱的列表进行线性循环,将数字相加,如果运行总和与最终总和相同,则返回 true。

Use the Gauss formula to precompute what the final sum will be:

final_sum = k * (k+1)
            ---------
                2

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.

各自安好 2024-12-14 09:14:20

您需要对数组进行排序。以下是一些流行选择的链接,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.

此生挚爱伱 2024-12-14 09:14:20

如果不允许有额外的空间(面试问题中的典型约束),那么您可以先对数组进行排序,然后从左到右顺序扫描排序后的数组,看看每个元素是否都比前一个元素大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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文