[英]Counting the number of inversions in a vector
背景资料:
这是Google每天的编码问题。
我们可以通过计算数组A的反转次数来确定数组A的“混乱程度”。 如果A [i]> A [j]但i <j,则两个元素A [i]和A [j]形成求逆。也就是说,较小的元素出现在较大的元素之后。
给定一个数组,计算它具有的反转次数,比O(N ^ 2)时间要快。
您可以假设数组中的每个元素都是不同的。
例如,一个排序列表的反转数为零。array [2,4,1,3,5]具有三个反转数:(2,1),(4,1)和(4,3)。array [5 ,,4,3,2,1]有十个反转:每个不同的对都形成一个反转。
蛮力解决方案:
auto num_inversions(std::vector<int>& nums)
{
int count = 0;
for (int i = 0; i <= nums.size(); ++i)
{
for (int j = i + 1; j < nums.size(); ++j)
{
if (nums[i] > nums[j])
++count;
}
}
return count;
}
更好的潜在解决方案:
我的想法是使用priority_queue来实现以下目标:
auto num_inversions1(std::vector<int>& nums)
{
auto compare = [](int lhs, int rhs)
{
return lhs > rhs;
};
std::priority_queue<int, std::vector<int>, decltype(compare)> q(compare);
for (auto num : nums)
q.push(num);
print_queue(q);
}
现在,如果我知道使用比较lambda的次数,那么我认为这将确定我的反转次数。 是否可以计算在优先级队列中使用lambda表达式的次数? 如果是这样,这种方法行得通吗?
更新:
按照提供的链接的建议,除了一个修改的mergesort之外,没有过多地看答案,我尝试了一下,但没有得到正确的结果。
这是我的代码:
#include <iostream>
#include <vector>
int merge(std::vector<int>& data, std::vector<int>& temp, int low, int middle, int high) {
// create a temporary array ... O(N) memory complexity !!!
// copy the data to a temporary array
for (int i = low; i <= high; i++) {
temp[i] = data[i];
}
int i = low;
int j = middle + 1;
int k = low;
int inv_count = 0;
// Copy the smallest values from either the left or the right side back
// to the original array
while ((i <= middle) && (j <= high)) {
if (temp[i] <= temp[j]) {
data[k] = temp[i];
i++;
}
else {
data[k] = temp[j];
j++;
inv_count = inv_count + (middle - i);
}
k++;
}
// Copy the rest of the left side of the array into the target array
while (i <= middle) {
data[k] = temp[i];
k++;
i++;
}
// Copy the rest of the right side of the array into the target array
while (j <= high) {
data[k] = temp[j];
k++;
j++;
}
return inv_count;
}
int merge_sort(std::vector<int>& data, std::vector<int>& temp, int low, int high)
{
int mid, inv_count = 0;
if (high > low)
{
mid = (low + high) / 2;
inv_count = merge_sort(data, temp, low, mid);
inv_count += merge_sort(temp, temp, mid + 1, high);
inv_count += merge(data, temp, low, mid, high);
}
return inv_count;
}
int sort(std::vector<int>& data, std::vector<int>& temp)
{
return merge_sort(data, temp, 0, data.size() - 1);
}
int main()
{
std::vector<int> data = { 2, 4, 1, 3, 5 };
auto n = data.size();
std::vector<int> temp(n, 0);
std::cout << "The number of inversions is " << sort(data, temp);
std::cin.get();
}
答案应该是3,但我只有1
使用计数器:
auto num_inversions1(std::vector<int>& nums)
{
int cmpCounter = 0;
auto compare = [&cmpCounter](int lhs, int rhs)
{
cmpCounter++;
return lhs > rhs;
};
std::priority_queue<int, std::vector<int>, decltype(compare)> q(compare);
for (auto num : nums)
q.push(num);
print_queue(q);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.