Java中将多行数组中的每行重复的数合拼
时间: 2024-03-01 18:52:32 浏览: 49
可以使用Java中的HashSet来实现该功能。具体步骤如下:
1. 定义一个HashSet,用于存储每行中出现过的数字
2. 遍历多行数组中的每一行,对于每行进行如下操作:
- 定义一个StringBuilder,用于存储该行中不重复的数字
- 遍历该行中的每个数字,如果该数字尚未被加入HashSet中,则将其加入HashSet和StringBuilder中
- 最终将StringBuilder中的内容转换为字符串,并将其存入一个新的数组中
3. 返回新的数组,其中每个元素为多行数组中的一行,重复的数字已经被合并为一个数字。
下面是示例代码实现:
```
public static int[][] mergeRepeatedNumbers(int[][] array) {
HashSet<Integer> set = new HashSet<Integer>();
List<int[]> result = new ArrayList<int[]>();
for (int[] row : array) {
StringBuilder sb = new StringBuilder();
for (int num : row) {
if (!set.contains(num)) {
set.add(num);
sb.append(num);
sb.append(" ");
}
}
if (sb.length() > 0) {
String str = sb.toString().trim();
String[] nums = str.split(" ");
int[] newRow = new int[nums.length];
for (int i = 0; i < nums.length; i++) {
newRow[i] = Integer.parseInt(nums[i]);
}
result.add(newRow);
}
}
return result.toArray(new int[result.size()][]);
}
```
阅读全文
相关推荐
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)