在两个排序数字之间查找缺失数字的最佳算法是什么?
What's the best algorithm to find a missing number between two sorted numbers?
好的,下面是一个例子:
我们有一个数组[1, 2, 3, 6, 7, 9, 15]
而且我们需要找到适合两个数字(如果已排序)的数字。它至少应该有助于在数组中创建一个由 3 个数字组成的序列。我们可以假设只有一个缺失的数字。
这种情况下的答案是 8
。我知道如何使用 in
运算符在 python 中强制执行此操作,但效率不高。
def find_missing_number(arr):
for num in arr:
if (
num in arr and
num + 1 not in arr and
num + 2 in arr
):
return num + 1
感谢任何语言解决方案。
查找距离为 2 的连续数字:
def find_missing_number(arr):
arr = sorted(arr) # you'll only need this, if arr is not yet sorted
for a, b in zip(arr, arr[1:]):
if b - a == 2:
return a + 1
我建议的逻辑是相同的。
对于 num = least to max least = 1 and max = 15 in this example
迭代并查看 loop 和 loop + 2 是否在数组中且 loop+1 不在数组中
这是 C++ 17 中的解决方案,
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> v1 {1, 2, 3, 6, 7, 9, 15};
auto const it = std::adjacent_find(v1.begin(), v1.end(),
[] (auto const a, auto const b) {
return b - a == 2;
} );
if (it == v1.end()) {
std::cout << "no matching\n";
} else {
std::cout << "the missing number: " << 1 + *it << '\n';
}
}
你可以使用一组来加快它的速度。并删除无意义的 num in arr
检查(这总是正确的,因为你正在做 for num in arr
)。
def find_missing_number(arr):
s = set(arr)
for num in arr:
if (num + 1 not in s) and (num + 2 in s):
return num + 1
好的,下面是一个例子:
我们有一个数组[1, 2, 3, 6, 7, 9, 15]
而且我们需要找到适合两个数字(如果已排序)的数字。它至少应该有助于在数组中创建一个由 3 个数字组成的序列。我们可以假设只有一个缺失的数字。
这种情况下的答案是 8
。我知道如何使用 in
运算符在 python 中强制执行此操作,但效率不高。
def find_missing_number(arr):
for num in arr:
if (
num in arr and
num + 1 not in arr and
num + 2 in arr
):
return num + 1
感谢任何语言解决方案。
查找距离为 2 的连续数字:
def find_missing_number(arr):
arr = sorted(arr) # you'll only need this, if arr is not yet sorted
for a, b in zip(arr, arr[1:]):
if b - a == 2:
return a + 1
我建议的逻辑是相同的。 对于 num = least to max least = 1 and max = 15 in this example
迭代并查看 loop 和 loop + 2 是否在数组中且 loop+1 不在数组中
这是 C++ 17 中的解决方案,
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<int> v1 {1, 2, 3, 6, 7, 9, 15};
auto const it = std::adjacent_find(v1.begin(), v1.end(),
[] (auto const a, auto const b) {
return b - a == 2;
} );
if (it == v1.end()) {
std::cout << "no matching\n";
} else {
std::cout << "the missing number: " << 1 + *it << '\n';
}
}
你可以使用一组来加快它的速度。并删除无意义的 num in arr
检查(这总是正确的,因为你正在做 for num in arr
)。
def find_missing_number(arr):
s = set(arr)
for num in arr:
if (num + 1 not in s) and (num + 2 in s):
return num + 1