如图下面2D数组中,找出每行都重复的元素。
4 | 67 | 34 | 90 |
---|---|---|---|
9 | 4 | 11 | 100 |
6 | 12 | 9 | 4 |
78 | 87 | 4 | 2 |
可见只有4是每行都出现的。
思路:
每行都重复的元素,那么重复的元素必定都在第一行。第一行的元素如果在其它行都出现,那么这个元素肯定是重复的。
-
用HashMap来实现,将第一行的元素存到HashMap中,元素为key,出现次数value为1,循环遍历其它行,如果元素已经存在HashMap中,则将value加1,不存在则略过。最后HashMap中value值等于行数的元素就是重复的。读者可以自己试一把,我这里就不实现 了,应该很简单的。
-
利用HashSet实现。将第一行的元素放入一个HashSet1中,第二行元素存另一个HashSet2中,利用retainAll方法保留两个HashSet相同的元素,再将HashSet2清空存第三行元素,再于HashSet1相交取相同部分,依次类推。。。最后HashSet1中的元素就是重复的元素。
例如上面的2维数组。
第一行元素存HashSet1:| 4 | 67 |34 |90|
第二行元素存HashSet2:| 9 | 4 |11| 100|
HashSet1.retainAll(HashSet2) —> 4
HashSet2清空存第三行元素:|6 |12| 9 |4|
HashSet1.retainAll(HashSet2) —> 4
HashSet2清空存第四行元素:|78| 87| 4 |2|
HashSet1.retainAll(HashSet2) —> 4最后HashSet1中的元素4就是每行都重复的元素
实现:
public static void findDuplicatedElementsInEachRow(int arraylist[][]) {
Set<Integer> expectedDuplicated = new HashSet<>();
Set<Integer> deleteRow = new HashSet<>();
boolean isDuplicated = true;
for (int i = 0; i < arraylist.length; i++) {
for (int j = 0; j < arraylist.length; j++) {
if (i == 0) {
expectedDuplicated.add(arraylist[i][j]);
} else {
deleteRow.add(arraylist[i][j]);
}
}
if (i != 0) {
expectedDuplicated.retainAll(deleteRow);
deleteRow.clear();
}
if (expectedDuplicated.size() == 0) {
isDuplicated = false;
break;
}
}
if (isDuplicated) {
System.out.println("the duplicated element in each row is: " + expectedDuplicated);
} else {
System.out.println("there is no element duplicated in each row");
}
}
完整代码:
import java.util.*;
public class Test {
public static void main(String[] args) {
testFindDuplicatedElementsInEachRow();
}
public static void testFindDuplicatedElementsInEachRow(){
int arrayList[][] = {{1, 2, 3, 4}, {5, 6, 7, 4}, {4, 5, 4, 5}, {4, 5, 4, 5}};
System.out.println("Check duplicated elements: ");
findDuplicatedElementsInEachRow(arrayList);
}
public static void findDuplicatedElementsInEachRow(int arraylist[][]) {
Set<Integer> expectedDuplicated = new HashSet<>();
Set<Integer> deleteRow = new HashSet<>();
boolean isDuplicated = true;
for (int i = 0; i < arraylist.length; i++) {
for (int j = 0; j < arraylist.length; j++) {
if (i == 0) {
expectedDuplicated.add(arraylist[i][j]);
} else {
deleteRow.add(arraylist[i][j]);
}
}
if (i != 0) {
expectedDuplicated.retainAll(deleteRow);
deleteRow.clear();
}
if (expectedDuplicated.size() == 0) {
isDuplicated = false;
break;
}
}
if (isDuplicated) {
System.out.println("the duplicated element in each row is: " + expectedDuplicated);
} else {
System.out.println("there is no element duplicated in each row");
}
}
}
结果:
Check duplicated elements:
the duplicated element in each row is: [4]
Process finished with exit code 0