我正在讨论一个有趣的问题,它在逻辑上似乎很容易理解,确实如此,但我想不出解决它的方法。
示例:
<块引用>数组 = [1, 2, 3, 3, 2]
所以我们从头到尾遍历,找到第一个重复的索引点,然后做绝对差。
数组中出现的元素是1, 2, 3。
1 => 不会出现在任何地方,所以它只是 0。
2 => 出现在索引点 2 和 5,所以 abs(2 (First) - 5 (Last)) = 3
3 => 出现在 3 和 4,所以 abs(3 - 4) = 1
然后我们把它们加起来:0 + 1 + 3 => 4
答案 0 :(得分:0)
我会遍历数组并构建一个从值到一对索引(第一次出现和最后一次出现)的映射。第一次遇到一个值时,我会创建一个对,其中两个值都是相同的索引,并且在任何后续出现时,更新最后一个索引。
然后,当地图准备好时,我会遍历它并总结每个元素的第一个和最后一个索引之间的差异:
int arr[] = { 1, 2, 3, 3, 2 };
int len = 5;
// Accumulate into the map
unordered_map<int, pair<int, int>> m;
for (int i = 0; i < len; ++i) {
int val = arr[i];
if (m.find(val) == m.end()) {
m[val] = make_pair(i, i);
} else {
m[val].second = i;
}
}
// Go over the map and accumulate the differences:
int sum = 0;
for (auto iter = m.begin(); iter != m.end(); ++iter) {
sum += (iter->second.second - iter->second.first);
}
cout << "Total differences " << sum << endl;