首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在二维数组中返回不同的列?

在二维数组中返回不同的列,可以通过遍历数组的每一行,将每一列的元素存储到一个集合中,然后返回该集合。

以下是一个示例的代码实现(使用Java语言):

代码语言:txt
复制
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Main {
    public static void main(String[] args) {
        int[][] matrix = {
                {1, 2, 3},
                {4, 5, 6},
                {7, 8, 9}
        };

        List<int[]> result = getDistinctColumns(matrix);
        for (int[] column : result) {
            for (int num : column) {
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }

    public static List<int[]> getDistinctColumns(int[][] matrix) {
        List<int[]> result = new ArrayList<>();
        Set<Integer> columnSet = new HashSet<>();

        int rows = matrix.length;
        int cols = matrix[0].length;

        for (int j = 0; j < cols; j++) {
            columnSet.clear();
            int[] column = new int[rows];
            for (int i = 0; i < rows; i++) {
                column[i] = matrix[i][j];
                columnSet.add(matrix[i][j]);
            }
            if (columnSet.size() == rows) {
                result.add(column);
            }
        }

        return result;
    }
}

运行以上代码,输出结果为:

代码语言:txt
复制
1 4 7 
2 5 8 
3 6 9 

以上代码中,getDistinctColumns方法接受一个二维数组作为参数,返回一个包含不同列的列表。在方法中,我们使用一个集合columnSet来存储每一列的元素,并判断是否有重复元素。如果集合的大小等于行数,则说明该列中的元素都是不同的,将该列添加到结果列表中。

对于云计算领域的相关知识,可以参考腾讯云的文档和产品介绍,例如:

请注意,以上链接仅作为示例,具体的产品和文档可能会有更新和变动。建议根据实际需求和腾讯云的官方文档进行查阅。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券