面试题目

1、题目

2、代码实现

 1 package com.wcy.eleven;
 2 
 3 import java.util.Arrays;
 4 
 5 public class ArrayTest {
 6  
 7     public int[][] getResult(int[][] a){
 8         int[][] b = new int[a.length][a.length];
 9         int[] temp = new int[a.length*a.length];
10         int num = 0;
11         for (int i = 0; i < b.length; i++) {
12             for (int j = 0; j < b.length; j++) {
13                 if (i>0 && j>0) {
14                     temp[num] = a[i-1][j-1];
15                     num++;
16                 }
17                 if (i>0) {
18                     temp[num] = a[i-1][j];
19                     num++;
20                 }
21                 if (i>0&&(j<a.length-1)) {
22                     temp[num] = a[i-1][j+1];
23                     num++;
24                 }
25                 if (j>0) {
26                     temp[num] = a[i][j-1];
27                     num++;
28                 }
29                 if (j<a.length-1) {
30                     temp[num] = a[i][j+1];
31                     num++;
32                 }
33                 if (j>0&&i<a.length-1) {
34                     temp[num] = a[i+1][j-1];
35                     num++;
36                 }
37                 if (i<a.length-1) {
38                     temp[num] = a[i+1][j];
39                     num++;
40                 }
41                 if (i<a.length-1&&j<a.length-1) {
42                     temp[num] = a[i+1][j+1];
43                     num++;
44                 }
45                 int[] result = new int[num];
46                 for (int j2 = 0; j2 < num; j2++) {
47                     result[j2] = temp[j2];
48                 }
49                 Arrays.sort(result);
50                 b[i][j] = result[result.length/2];
51                 num = 0;
52             }
53         }
54         return b;
55     }
56     
57     public static void main(String[] args) {
58         ArrayTest test = new ArrayTest();
59         int[][] a = {{5,85,4,2,68},{78,82,75,41,14},{79,47,38,1,47},{1,2,14,65,13},{96,87,32,14,21}};
60         int[][] result = test.getResult(a);
61         for (int i = 0; i < a.length; i++) {
62             for (int j = 0; j < a.length; j++) {
63                 if (j == a.length-1) {
64                     System.out.print(result[i][j]);
65                 }else {
66                     System.out.print(result[i][j] + " ");
67                 }
68             }
69             System.out.println();
70         }
71     }
72 }
原文地址:https://www.cnblogs.com/wangchaoyuan/p/6052010.html