看到好多面试过算法的人都遇到这个玩意,觉得自己也没做过,那就虚心学习以备不时之需。我随便翻了下别人的博客,自己也手写了下,搞懂方法就行。下面把东西贴在下面~~
图示
import org.junit.Test;
import static java.lang.System.out;
/**
* ClassName:Maintest
*
* @author: zhengkw
* // * @description: 测试
* @date: 20/02/01下午 7:34
* version:
* @since: jdk 1.8
*/
public class Maintest {
@Test
public void VortexNum() {
//这个是题目
int attrs[][] = {
{0, 1, 2, 3},
{11, 12, 13, 4},
{10, 15, 14, 5},
{9, 8, 7, 6},
// {9, 8, 7, 6},
};
VortexNumber vortexNumber = new VortexNumber();
vortexNumber.outputNum(attrs);
}
}
功能代码
import javax.imageio.stream.ImageInputStream;
import static java.lang.System.out;
/**
* ClassName:VortexNumber
*
* @author: zhengkw
* @description: 回形数
* @date: 20/02/02下午 3:20
* version:
* @since: jdk 1.8
*/
public class VortexNumber {
/**
* @param vortxNub
* @return void
* @description 定义一个方法 入参一个数组 返回一个一维有序列
* @date 20/02/02 下午 3:43
* @author zhengkw
*/
public void outputNum(int[][] vortxNub) {
//给定一个n阶回形数组 记录总个数 下图为row 4 col 3
// {{1, 3, 5},
// {11,15,16},
// {12,14,17},
// {4 ,8, 9}}
int count = 0, col = 0, row = 0;
try {
col = vortxNub[0].length;
row = vortxNub.length;
count = col * row;
} catch (Exception e) {
out.println("数组为空");
e.printStackTrace();
}
//定义脚标 vortxNub[i][j]
int i = 0, j = 0;
//当count不为0时即执行下面代码
while (count > 0) {
//输出上边
for (int m = 1; m < col; m++) {
out.print(vortxNub[i][j] + "\t");
//count=count-1;
count -= 1;
//i不变j++继续遍历
j++;
}
//输出右边
for (int m = 1; m < row; m++) {
out.print(vortxNub[i][j] + "\t");
count -= 1;
//j不变i++继续遍历
i++;
}
//输出下面(根据提示是右到左)
for (int m = 1; m < col; m++) {
out.print(vortxNub[i][j] + "\t");
//count=count-1;
count -= 1;
//i不变j--变向遍历
--j;
}
//输出左边(自下而上)
for (int m = 1; m < row; m++) {
out.print(vortxNub[i][j] + "\t");
//count=count-1;
count -= 1;
//j不变i--变向遍历
--i;
}
//每次遍历一环时起始位置变化
i++;
j++;
//每次遍历一环横竖各少两个边,所以减去
row = row - 2;
col = col - 2;
}
}
}