c++ - 想出解决方案?

标签 c++ algorithm

给出了一个由 N 个不同的整数组成的零索引数组 A。该数组包含 [1..(N + 1)] 范围内的整数,这意味着正好缺少一个元素。

您的目标是找到缺失的元素。

写一个函数:

int solution(int A[], int N); 

给定一个零索引数组 A,返回缺失元素的值。

例如,给定数组 A 使得:

A[0] = 2 A[1] = 3 A[2] = 1 A[3] = 5

函数应该返回 4,因为它是缺少的元素。

假设:

N is an integer within the range [0..100,000];
the elements of A are all distinct;
each element of array A is an integer within the range [1..(N + 1)].

复杂度:

expected worst-case time complexity is O(N);
expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).

它不适用于有两个元素的情况

int solution(vector<int> &A) {

    sort(A.begin(), A.end());
    int missingIndex = 0;

    for (int i = 0; i < A.size(); i++)
    {
        if ( i != A[i]-1)
        {
            missingIndex = i+1;
        }

    }
    return missingIndex;
}

最佳答案

由于您的数组是零索引的并且数字是从 1 到 N+1,因此语句应该是:

if ( i != A[i]-1)

此外,您应该在更新 missingIndex 后立即跳出 for 循环,因为缺失元素之外的所有条目都应具有 (i != A[i]-1)

此外,由于排序,您的解决方案是 O(NlogN) 而不是 O(N)。

相反,您可以对数组 (使用 unsigned long long int) 中的所有元素求和,并检查它与 N(N+1)/2 的区别

关于c++ - 想出解决方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29164936/

相关文章:

c++ - Visual 2010 的 LUA 编译错误 "external symbol "struct lua_State * __cdecl luaL_newstate(void)”

c++ - 是否可以将函数导入到命名空间,但不能导出它?

algorithm - 如何划分数值曲线

algorithm - 在使用线性探测构建散列表以解决冲突时,额外项是始终添加到散列中还是仅在发生冲突时添加?

algorithm - 贪心算法有没有可能也是动态规划算法?

c++ - OpenSSL 静态库太大,有什么替代方法或方法可以减小它的大小吗?

c++ - 类型转换指向 unique_ptr 的普通指针是一种不好的做法吗?

c++ - 不使用系统时钟的时间测量

algorithm - 使用深度优先搜索的三角形最大和

arrays - 在大小为 N 且元素范围为 0 到 N-1 的整数数组中查找总和为 X 的对