以下方法均借鉴了各路大神的思想,放在这里只是为了给自己提供个方便,重要的事情说三遍,不是原创不是原创不是原创!~
1.回型打印二位数组
例如:
打印结果:1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10
//回型打印二位数组
public static void getValue(int[][] arry){
int n = arry.length-1;
int top = 0,bottom = n;
int left = 0,right = n;
while (top<=bottom||left<=right){
//左-右
for (int i=left;i<=right;i++){
System.out.print(arry[top][i]+" ");
}
top++;
//上-下
for (int i=top;i<=bottom;i++){
System.out.print(arry[i][right]+" ");
}
right--;
//右-左
for (int i =right;i>=left;i--){
System.out.print(arry[bottom][i]+" ");
}
bottom--;
//下-上
for (int i=bottom;i>=top;i--){
System.out.print(arry[i][left]+" ");
}
left++;
}
}
// 写个简单的测试方法
public static void main(String[] args) {
int[][] array={{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
getValue(array);
}
2.二叉树遍历
例如:
打印结果:1 2 4 8 9 5 3 6 7
//创建节点
static class Node{
Node left;
Node right;
int date;
Node(int date){
left = null;
right = null;
this.date=date;
}
}
//构建二叉树
public static List<Node> createTree(int array[]){
List<Node> nodeList = new ArrayList<>();
if (array.length<1){
return nodeList;
}
for (int i=0;i<array.length;i++){
nodeList.add(new Node(array[i]));
}
int index = array.length/2-1;
for (int i=0;i<index;i++){
//创建左节点
nodeList.get(i).left = nodeList.get(i*2+1);
nodeList.get(i).right = nodeList.get(i*2+2);
}
nodeList.get(index).left = nodeList.get(index*2+1);
if (array.length%2==1){
nodeList.get(index).right = nodeList.get(index*2+2);
}
return nodeList;
}
//根前后 三种方式调整这里的顺序即可
public static void getNodeDate(Node node){
if (node==null){
return;
}
System.out.print(node.date+" ");
getNodeDate(node.left);
getNodeDate(node.right);
}
public static void main(String[] args) {
int array[] = {1,2,3,4,5,6,7,8,9};
List<Node> nodeList = createTree(array);
Node head = nodeList.get(0);
getNodeDate(head);
}
3.判断数组中是否有回文数组
例如:1,2,3,4,5,6,7,8,7,6,5,9,8,7,1,2
回文数字:5,6,7,8,7,6,5
//判断后续数组中是否有相同数字,并返回其下标
public static int getSameValue(int [] array,int key,int low){
if (array.length<1){
return -1;
}
for (int i = low;i<array.length;i++){
if (array[i]==key){
return low+i;
}
}
return -1;
}
//判断是否有回文数
public static boolean haveRang(int[] array,int low){
if (array.length<1){
return false;
}
int high = array.length-1;
for (int i = low,j=high;low<high;low++,high--){
if (array[i]!=array[j]){
return false;
}
}
return true;
}
public static void main(String[] args) {
boolean falg = false;
int[] array={1,2,3,4,5,6,7,8,7,6,5,9,8,7,1,2};
for (int i=0;i<array.length;i++){
if (-1!= getSameValue(array,array[i],i)){
if (haveRang(array,i)){
falg = true;
}
}
}
System.out.println(falg);
}