Redian新闻
>
details 2nd smallest element in an array
avatar
details 2nd smallest element in an array# JobHunting - 待字闺中
g*v
1
我对真个算法都非常清楚,唯一不明白的是些实现问题:
怎样去保存曾经比较过的数字。
比如:
5 4 2 6 -1 -5 7 8
先找到最小的数字是-5,然后需要在和它比较过的数字中找个最小的,想知道怎样找到去比
较过的数字?
谢谢
avatar
g*v
2
难道需要保存每一个element的比较对象么
avatar
s*y
3
int smallest = INT_MAX;
int second_smallest = INT_MAX;
for (int i = 0; i < sizeof(input)/sizeof(int);i++) {
if (second_smallest < input[i]) {
if (smallest < input[i]) {
second_smallest = smallest ;
smallest = input[i];
} else {
second_smallest = input[i];
}
}
}
return second_smallest;
avatar
d*e
4
You sure?
5 4 2 6 -1 -5 7 8
4 2 -1 -5
-1 -5
第一轮 4次比较,第二轮 6次比较, 第三轮3次比较。

到去比

【在 g****v 的大作中提到】
: 我对真个算法都非常清楚,唯一不明白的是些实现问题:
: 怎样去保存曾经比较过的数字。
: 比如:
: 5 4 2 6 -1 -5 7 8
: 先找到最小的数字是-5,然后需要在和它比较过的数字中找个最小的,想知道怎样找到去比
: 较过的数字?
: 谢谢

avatar
g*v
5
最优算法是n+lgn-2. CLR书上的一个课后题。

【在 s*****y 的大作中提到】
: int smallest = INT_MAX;
: int second_smallest = INT_MAX;
: for (int i = 0; i < sizeof(input)/sizeof(int);i++) {
: if (second_smallest < input[i]) {
: if (smallest < input[i]) {
: second_smallest = smallest ;
: smallest = input[i];
: } else {
: second_smallest = input[i];
: }

avatar
g*v
6
应该是这样:
5 4 2 6 -1 -5 7 8
4 2 -5 7
2 -5
-5
然后再在{2,7,-1}中找最小的,但现在问题是怎样得到{2,7,-1}

【在 d******e 的大作中提到】
: You sure?
: 5 4 2 6 -1 -5 7 8
: 4 2 -1 -5
: -1 -5
: 第一轮 4次比较,第二轮 6次比较, 第三轮3次比较。
:
: 到去比

avatar
f*i
7
In this case, every element is unique, therefore, a possible way is to
create a hashtable which for each element, which contains all the numbers it
compared before.
Hashtable>
therefore, it is O(logn) approach, but we need O(n) space.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。