减少以下程序中的执行时间

时间:2018-02-27 13:07:47

标签: c++ optimization time-complexity

我需要针对以下问题优化我的答案,而不会超出时间限制(0.5s)。这不是作业,竞赛或面试问题。我正在学习自己的编程为了好玩,我在网上找到了这个。

给定一个仅包含1到a.length范围内的数字的数组a,找到第二个匹配项具有最小索引的第一个重复数字。换句话说,如果有多于1个重复的数字,则返回第二次出现的索引小于另一个出现的第二次出现的索引的数量。如果没有这样的元素,则返回-1。

这是我的答案:

int firstDuplicate(std::vector<int> a) 
{
    int arrLen = a.size();
    int dupIndex = -1;
    int seen[arrLen];

    for (int i = 0; i < arrLen; i++)
        seen[i] = 0;

    for (int i = 0; i < arrLen && dupIndex == -1; i++)
    {
        for (int j = 0; j < arrLen && dupIndex == -1 && seen[j] != 0; j++)
            if (a[i] == seen[j])
                dupIndex = seen[j];
        seen[i] = a[i];
    }

    return dupIndex;
}

[输入] array.integer a
保证约束:

1 ≤ a.length ≤ 105,
1 ≤ a[i] ≤ a.length

我应该如何优化代码以及有关程序优化的因素是什么? (是的,我是编程的新手)

2 个答案:

答案 0 :(得分:1)

无需其他答案。我想通了。

int firstDuplicate(std::vector<int> a) 
{
    int arrLen = a.size();
    int dupIndex = -1;
    int seen[arrLen];

    for (int i = 0; i < arrLen; i++)
        seen[i] = 0;

    for (int i = 0; i < arrLen && dupIndex == -1; i++)
    {
        if (seen[a[i]] == a[i] * -1)
            dupIndex = a[i];
        else
            seen[a[i]] = a[i] * -1;
    }

    return dupIndex;
}

答案 1 :(得分:-2)

首先(天真)优化:在i+1开始内循环。

第二个(也是天真的,因为它使用了相当多的内存)优化:分配长度为a.length的数组,初始化为-1。然后,迭代一次数据,一旦找到数字,就存储其索引。如果已经找到索引,您可以通过检查-1来检测到该索引,并且您有重复索引。

相关问题