所以我在Java中遇到了这个问题,想要删除出现两次以上的数字列表,但保留顺序,以及前两次出现的情况。
例如,如果列表为 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2, 10
预期输出为 2, 3, 5, 4, 5, 2, 4, 3, 10
我尝试了几种方法,包括使用计数器 int 来跟踪发生的情况并将其过滤掉,但我不知道如何去做
class DeDup {
// function to find the element occurring more than 3 times
static void get2Occurrences(int arr[]) {
int i;
int count = 0;
for (i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length; j++) {
if (arr[i] == arr[j])
count++;
}
if (count < 3 && count > 0) {
//return arr[i];
System.out.print(arr[i] + ", ");
} else {
for (int k = 2; k > 0; k--) {
System.out.print(arr[i] + ", ");
}
}
}
}
// driver code
public static void main(String[]args) {
int arr[] = new int[]{ 2, 3, 5, 4, 5, 2, 4, 3, 5, 2, 4, 4, 2, 10 };
//expected output: 2, 3, 5, 4, 5, 2, 4, 3, 10
//int n = arr.length;
get2Occurrences(arr);
}
}
预期输出为 2, 3, 5, 4, 5, 2, 4, 3, 10
但我有 2, 2, 3, 3, 5, 5, 4, 4, 5, 5, 2, 2, 4, 4, 3, 3, 5, 5, 2, 2, 4, 4, 4, 4, 2, 2, 10, 10,
最佳答案
我会使用一对 Set
来完成此操作:Set.add
返回一个 boolean 值,指示是否添加了该元素。因此:
boolean b = set1.add(num) || set2.add(num);
如果它被添加到任一集合中,则为 true
- 并且仅当它已在 set1
中时才会尝试将其添加到 set2
中> - 和 false
否则,意味着它已经存在于两个集合中。
Set<Integer> set1 = new HashSet<>();
Set<Integer> set2 = new HashSet<>();
for (Integer a : arr) {
if (set1.add(a) || set2.add(a)) {
System.out.print(a + ", ");
}
}
关于java - 如何删除出现两次以上的重复数字,但保留前两次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55406941/