我想在动态数组中查找重复元素。在大多数情况下它有效,但它如何适用于这种情况。我在给定的数组中找到重复的元素。但是有一个问题,我的重复元素也可以重复。我该如何解决那部分。
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
int* dynArr = new int[n];
for (int i = 0; i < n; i++) {
std::cin >> dynArr[i];
}
for(int i = 0; i < n; i++){
for(int j = i + 1; j < n; j++){
if(dynArr[j] == dynArr[i]){
std::cout<<dynArr[j]<<" ";
break;
}
}
}
}
我对这部分有问题。当我输入长度为 6 的数组和元素 {1,1,2,1,2,2} 时。 我得到了 (1,1,2,2)。 但我只需要得到 1,2。
input 6
1 1 2 1 2 2
output 1 1 2 2
但必须
output 1 2
答案 0 :(得分:3)
这是一个简单快速的解决方案。
std::map<int,size_t> element_count;
for(int i = 0; i < n; i++){
if ( ++element_count[dynArr[i]] == 2 ){
// Only report on the second occurrance
std::cout<<dynArr[j]<<" ";
}
}
答案 1 :(得分:0)
static class Node<I> {
public I id;
public I parentId;
public int depth;
public Node(I id) {
this.id = id;
this.parentId = id;
}
@Override
public String toString() {
return id + " | " + parentId + " | depth: " + depth;
}
}
public static <I, T extends Node<I>> List<T> generateTreeStream(int count,
int maxDepth,
Supplier<T> supplier) {
Collector<T, List<T>, List<T>> collector = Collector.of(
ArrayList::new,
(list, node) -> {
if (!list.isEmpty()) {
int random = ThreadLocalRandom.current().nextInt(0, list.size());
T parent = list.get(random);
if (parent.depth < maxDepth) {
node.parentId = parent.id;
node.depth = parent.depth + 1;
}
}
list.add(node);
},
(left, right) -> {
left.addAll(right);
return left;
}
);
return IntStream.range(0, count)
.mapToObj(i -> supplier.get())
.collect(collector);
}
请注意,此代码根本不会快速运行,仅在操作不需要多次运行时才使用它,但它只会显示重复的单个数字。它肯定需要进一步优化
答案 2 :(得分:0)
您只需使用两个 std::set<int>
即可完成。
#include <set>
#include <iostream>
int main() {
unsigned n;
std::cin >> n;
int count = 0;
std::set<int> all;
std::set<int> redundant;
for (int i = 0; i < n; i++) {
int input = 0;
std::cin >> input;
// You cant enter the entry because its present. This will return a std::pair<,> with the second value false.
if (!all.insert(input).second)
redundant.insert(input); // We store this in another set so we dont duplicate the redundant entries.
}
for (auto itr = redundant.begin(); itr != redundant.end(); itr++)
std::cout << *itr << " ";
}