2016-11-20 102 views
0

我正在为Java中的Algorithms类的项目工作,并且我无法解决这个问题。同时比较二维数组的层

我有一个尺寸为[m] [n]的二维数组,其中m和n可以根据输入而波动。我想将这些值压缩到一个单维数组中,该数组的值是二维数组中任何垂直列的最低值。这里是数组的两个样本。

样品1个输入:

3.0, 4.0, 2.0, 3.0, 4.0, 2.0, 1.0, 2.0, 0.0, 3.0, 3.0 
0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 3.0, 2.0, 2.0 

样品1个输出:

0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 1.0, 2.0, 0.0, 2.0, 2.0 

样品2输入:

0.0, 1.0, 1.0, 2.0, 3.0, 1.0, 2.0, 3.0, 3.0, 2.0, 2.0 
2.0, 3.0, 1.0, 0.0, 1.0, 3.0, 2.0, 3.0, 3.0, 4.0, 2.0 
1.0, 2.0, 2.0, 3.0, 4.0, 0.0, 1.0, 2.0, 2.0, 1.0, 3.0 
1.0, 2.0, 0.0, 1.0, 2.0, 2.0, 1.0, 2.0, 2.0, 3.0, 1.0 
2.0, 3.0, 1.0, 2.0, 3.0, 1.0, 0.0, 1.0, 1.0, 2.0, 2.0 

样品2输出:

0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0 

这是我要排序的逻辑是这样的:

loop through the 2-d array 
at every vertical index, compare all values within the vertical index, 
output lowest value to single dimensional array 

我相信这是一个有些简单的问题,但我不能换我围​​绕如何做到这一点正确的头。感谢您提供任何建议!

+0

[一(http://meta.programmers.stackexchange.com/questions/6166/open-letter-to-students-with-homework-problems) –

回答

3

试想一下,输入[M] [N] M.将你的行n将是你的列,所以你必须遍历逐列得到该列中的最低值:

int[] output = new int[n]; 
for(i = 0; i < n; i++) 
    output[n] = input[0][n]; 
for(i = 0; i < n; i++) 
    for(k = 0; k < m; k++) 
     if(output[n] > input[m][n]) 
      output[n] = input[m][n]; 
+0

'if(output [n]> input [ m] [n])'这种情况在这里总是失败,'output [n]'总是零且小于2-d数组中的值。我认为第一个循环需要像'for(i = 0; i Hemakumar

+0

@Hemakumar你是对的,编辑我的答案。 – DoanCan

+0

'output [n] = input [0] [n];''我认为它的'output [n] = input [n] [0];' – Hemakumar