假设我有一个3 * 3阵列(2D阵列):
1 2 4
1 5 7
2 4 8
所以1,2和4出现不止一次。我想得到的结果是3。 我怎么能这样做?
答案 0 :(得分:1)
这是一种蛮力直接计算重复的方式。将2d数组转换为1d数组(List<Integer>
),然后循环遍历1d数组,在找到它们时计算重复项并将其删除,这样您就不会多次计算它们。
public static void main(String[] args) throws Exception {
int[][] _2dArray = {
{ 1, 2, 4 },
{ 1, 5, 7 },
{ 2, 4, 8 }
};
// Convert to a flat 1d array
List<Integer> flatArray = new ArrayList();
for (int[] row : _2dArray) {
for (int col : row) {
flatArray.add(col);
}
}
// Count and remove duplicates as you find them
int dupCount = 0;
for (int i = 0; i < flatArray.size(); i++) {
boolean dupFound = false;
for (int j = i + 1; j < flatArray.size(); j++) {
if (flatArray.get(i) == flatArray.get(j)) {
dupFound = true;
// Remove duplicate found in inner loop
flatArray.remove(j);
j--;
}
}
if (dupFound) {
dupCount++;
// Remove duplicate found in outer loop
flatArray.remove(i);
i--;
}
}
System.out.println(dupCount);
}
结果:
3
如果你对溪流感兴趣,你也可以选择这条路线。它将数组中的所有数字组合成一个数字为关键字的地图,该数字的频率为该值。然后,我们只保留值> gt的键/值对。 1(重复)。
public static void main(String[] args) throws Exception {
int[][] _2dArray = {
{ 1, 2, 4 },
{ 1, 5, 7 },
{ 2, 4, 8 }
};
// Convert to a flat 1d array
int[] flatArray = Arrays.stream(_2dArray)
.flatMapToInt(Arrays::stream)
.toArray();
//Count duplicates
Object[] duplicates = Arrays.stream(flatArray).boxed()
// Group all integers together
.collect(Collectors.groupingBy(i -> i, Collectors.counting()))
// Keep key/value pairs whose value > 1
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.toArray();
System.out.println(duplicates.length);
}
结果:
3
答案 1 :(得分:1)
以下是在不使用集合的情况下查找2D矩阵中重复元素计数的解决方案 公共类DuplicateElementsCountIn2DMetrixWithoutUsingCollections {
public static void main(String args[]){
String[][] matrix = {{"1","2","1","3",},{"7","6","null","2",},{"5","6","3","null",},{"3","10","9","5",}};
System.out.println(findDuplicate(matrix));
}
public static int findDuplicate(String[][] matrix){
String strArr[] = new String[(matrix.length)*(matrix[0].length)];
int count = 0;
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matrix[0].length; j++){
for(int k = 0; k < matrix.length; k++){
for(int l = 0; l < matrix[0].length; l++){
if((i!=k || j!=l)){
if(matrix[i][j] == matrix[k][l]){
int x = 0;
boolean flag = false;
while(strArr[x] != null){
if(null != matrix[i][j] && matrix[i][j].equals(strArr[x])){
flag = true;
}
x++;
}
if(flag==false){
strArr[count] = matrix[i][j];
count++;
}
}
}
}
}
}
}
return count;
}
}
6
注意:1,2,3,6,null在矩阵中重复,因此计数为6