伪代码查找列表中多次出现的数字
我有一个像 1,2,199,100,8,100,199,1001,5,9
这样的系列,我必须编写一个伪代码来找出上面列表中出现多次的数字。我可以清楚地看到 199 和 100 在列表中出现两次,这应该是答案,但是我应该如何为其编写伪代码? 我的逻辑是这样的:
array x = {1,2,199,100,8,100,199,1001,5,9}
array y
array j
for(int i = 0;i< 9; i++){
if x[i] exists in y
j[i] = y
else
y[i] = x
}
I have a series like 1,2,199,100,8,100,199,1001,5,9
and I got to write a pseudo code to find out the numbers which appear more then once in the above list. I can clearly see that 199 and 100 appear twice in the list and that should be the answer but how should I write the pseudocode for it?
My logic is something like this:
array x = {1,2,199,100,8,100,199,1001,5,9}
array y
array j
for(int i = 0;i< 9; i++){
if x[i] exists in y
j[i] = y
else
y[i] = x
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用快速排序或合并排序 (n log n) 对列表进行排序,然后对列表进行一次遍历,将当前数字与之前的 O(n) 进行比较。如果先前的数字等于当前的数字,则您有一个重复的数字。
编辑:
Sort the list with quick sort or merge sort (n log n) then do a single pass over the list comparing the current number to the previous O(n). If the previous number equals the current then you have a duplicate.
EDIT:
通过exists() 检查,这看起来与冒泡排序具有相同的性能。如果您对数组进行排序(使用更快的排序),然后再执行一次额外的操作来识别重复项,那么可能会更快。
如果我正确理解你的伪代码,它似乎有一个错误。难道不应该更像是:
With the exists() check this looks like it would have the same performance as a bubble sort. It would probably be faster if you sorted the array (with a faster sort) then did one extra pass to identify the dupes.
If I understand your pseudo code correctly it seems to have a bug. Shouldn't it be more like:
假设您仅限于使用基本类型而不能使用 java.util.Collections,您可以像这样工作:
下面是翻译为 Java 的伪代码:
Assuming you're restricted to only using primitive types rather than being able to use
java.util.Collections
, you could work it like this:Here's the pseudocode translated to Java: