数组算法经典实例
按照以下步骤编码:
1.分配两个5*5数组a和b,数组a按照以下所示赋值,
5,85,4,2,68
18,82,75,41,14
79,47,38,1,47
1,2,14,65,13
96,87,32,14,21;
对于数组中的每一个元素a[i][j],从它的相邻元素中选取中间值填入b[i][j]中,打印数组b.
例如:a[0][2]的相邻元素为85,82,75,41,2,升序(降序也可以)排列后为:2,41,75,82,85,取中间值方法:
中间值索引 = 相邻元素个数/2
即5/2 = 2,中间值为75,将75填入b[0][2]位置。
a[2][1]的相邻元素为78,82,75,79,38,1,2,14,排序后为1,2,14,38,75,78,79,82,中间值为75,填入b[2][1]。
以此类推,求出b[i][j]并打印。
答案:
package com.example.demo; import java.util.ArrayList; import java.util.List; /** * @author tobiasy */ public class Test { public static int getResult(int m,int n) { int[][] a = { {5,85,4,2,68}, {18,82,75,41,14}, {79,47,38,1,47}, {1,2,14,65,13}, {96,87,32,14,21} }; int[] x = {m-1,m,m+1}; int[] y = {n-1,n,n+1}; List<Integer> list = new ArrayList<>(); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { if (x[i] >= 0 && y[j] >= 0 && x[i] < 5 && y[j] < 5) { if (i==1&&j==1) { }else { list.add(a[x[i]][y[j]]); } } } } int[] result = new int[list.size()]; for (int i = 0; i < list.size(); i++) { int num = list.get(i); result[i] = num; } for (int i = 0; i < result.length; i++) { for (int j = 0; j < result.length; j++) { if (result[i] > result[j]) { int temp = result[i]; result[i] = result[j]; result[j] = temp; } } } return result[result.length/2]; } public static void main(String[] args) { int[][] b = new int[5][5]; for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { int res = getResult(i,j); b[i][j] = res; } } //打印方式可自行定义 for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) { System.out.print(b[i][j]+","); } System.out.println(); } } }
运行结果:
82,18,75,41,14,
79,38,38,14,41,
18,18,41,38,14,
79,38,32,14,21,
2,14,14,21,14,