c++ - 找到第二个最小值

标签 c++ arrays time-complexity minimum

我想在数组列表中找到第二个最小值。这是我的代码。有更好的方法吗?

int main(){
    int a[5]={7,5,45,89,12};
    int smallest=a[0];
    int index;
    for(int i=0;i<5;i++){
        if(a[i]<smallest){
            smallest=a[i];
            index=i;
        }
    }

    smallest=a[0];
    for(int i=0;i<5;i++){
        cout<<i;
        if((a[i]<smallest )&& (i!=index)){
            smallest=a[i];
        }
    }
    cout<<"second smallest value is: "<<smallest;  

此代码在 O(n) 时间内运行?对于第一个循环,它需要 n 个步骤,对于另一个 for 循环,它也需要 n 个步骤。因此总共需要 O(n) 时间复杂度。
这是对的吗?如果我错了,有人可以纠正我吗

最佳答案

是的, O(n),但实际上没有必要遍历列表两次。

您可以通过存储最小值和次小值来完成一次。

例如,考虑以下伪代码:

smallest = a[0]
second = a[1]
if second < smallest:
    swap second with smallest
for each index 2 thru a.size - 1 inclusive:
    if a[index] < smallest:
        second = smallest
        smallest = a[index]
    else:
        if a[index] < second:
            second = a[index]

也是 O(n) 但它只遍历列表一次,而不是两次。最后,second 保持第二高的值。

请记住,列表 {1, 1, 2} 中第二高的值是 1。如果您想以不同的方式处理重复项,只需稍作修改即可。


在 Python 中用示例作为概念证明来实现它,显示结果:

a = [1,45,2,96,4,35]
smallest = a[0]
second = a[1]
if second < smallest:
    smallest, second = second, smallest
for index in range (2, len(a)):
    if a[index] < smallest:
        second = smallest
        smallest = a[index]
    else:
        if a[index] < second:
            second = a[index]
print smallest
print second

它的输出是:

1
2

作为最小和第二小的数字。

关于c++ - 找到第二个最小值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26335400/

相关文章:

python - python __getitem__()方法中LinkedList的实现

algorithm - 算法的渐近行为和Big O比较

c++ - 为什么 for(class A{} fkldsjflksdjflsj;;) 可以编译?

c++ - 具有不同保护级别的访问器

javascript - 使用 JavaScript 删除字符串中注释标记后面的文本和空格 - 在字符串中创建新行

java - "deck shuffling"程序 : getting unexpected zeroes in results Java 出现问题

math - T(n) = (T(n-1) + n!) 的时间复杂度是多少?

c++ - 确定字节数组是否包含 ANSI 或 Unicode 字符串?

c++ - 类成员函数的地址

c - 为什么我们可以在数组中插入比数组所能容纳的更多的元素