测试一系列数字以确保它们符合序列 1,2,3...n
我正在尝试找到一个稍微更优雅的解决方案来查找数字序列是否有序。这是一个网络表单,我让用户有机会对项目进行编号并设置订单。我知道最大项目数,并且应该始终从 1 开始。
现在(我知道这是不正确的)我测试以确保所有数字都不同并且加起来达到应有的值(例如,对于我测试的三个项目,它加起来为 6)。有谁有更好/更准确的(因为有可能破坏我的)解决方案?我正在使用 php,但我真正想要的是逻辑,因此您的示例可以是伪代码或任何相对易于阅读的语言。
I am trying to find a slightly more elegant solution to find if a sequence of numbers is in order. This is for a web form, and I am giving the user a chance to number items and that will set up the order. I know the maximum number of items, and it should always start at one.
Right now (I know it is not correct) I test to make sure all the numbers are different and add up to what it should (e.g. for three items I test it adds to 6). Does anyone have a better/more accurate (since it is possible to go break mine) solution? I am using php, but what I really want is logic so your example could be in pseudo-code or any relatively easy to read language.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需对用户输入的数字进行排序,然后查看它们是否与您递增 1 的索引匹配。
对于
Sort
部分,存在多种排序算法:快速排序,直接插入< /a>,Heapsort 等。只需选择一个适合您的需求并进行搜索即可找到现成的过程网络。您选择的语言甚至可能有一些内置的排序算法,因此您甚至可能不需要看那么远。Just sort the user-input numbers, and see if they match an index that you increment by 1.
For the
Sort
part, there exists a variety of sorting algorithms: Quicksort, Straight insertion, Heapsort, etc. Just pick one that fits your needs and do a search to find a ready-made procedure on the web. Your language of choice may even have some built-in sorting algorithms, so you might not even need to look that far.由于您知道最大项目数,因此您可以通过简单地分配布尔数组并填充它来避免排序。在伪代码中:
这具有
O(n)
时间复杂度的优点,而不是最好情况的O(n log n)
- 这可能并不重要对于小型数据集,但对于较大的数据集可能会变得很重要。您还应该考虑到这样的事实:这比就地排序具有更高的空间复杂度,因为它使用等于输入大小的数组。这使得排序选项的空间复杂度为
O(n)
,而不是O(1)
。与往常一样,您通常可以根据需要权衡空间与时间。
Since you know the maximum number of items, you can avoid a sort by simply allocating a boolean array and populating it. In pseudocode:
This has the advantage of being
O(n)
time complexity rather than a best-case sort ofO(n log n)
- that probably won't matter for small data sets but it may become important for larger one.You should also take into account the fact that this has a higher space complexity than an in-place sort since it uses an array equalt to the input size. That makes it
O(n)
space instead of theO(1)
for the sort option.As always, you can generally trade off space for time depending on your needs.
如果您已经确定这些数字都不同,则只需检查最小值和最大值。只有 n 个不同的数满足 1 <= x <= n。
If you already established that the numbers are all different, just check the minimum and the maximum values. There are only n different numbers which satisfy 1 <= x <= n.