import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix int整型二维数组 * @return int整型一维数组 */ public static int[] spiralTravelCounterClockwise (int[][] matrix) { // write code here LinkedList<Integer> linkedList = new LinkedList<>(); int count = 0; int m=0; while (linkedList.size()<matrix.length*matrix[0].length){ int n = count; for(m = count;m < matrix.length-count;m++){ linkedList.add(matrix[m][n]); } m--; for(n = 1+count;n < matrix[0].length-1-count;n++){ linkedList.add(matrix[m][n]); } n = matrix[0].length-1-count; for(m = matrix.length-1-count;m >= count;m--){ linkedList.add(matrix[m][n]); } m++; for(n = matrix[0].length-2-count;n >= 1+count;n--){ linkedList.add(matrix[m][n]); } count++; } int[] arr = new int[matrix.length*matrix[0].length]; for(int i=0;i<arr.length;i++){ arr[i] = linkedList.get(i); } return arr; } }
本题考察的知识点是数组遍历,所用编程语言为java。
首先设立一个循环次数,从左上到坐下,从坐下到右下,再从右下到右上,最后再从右上到左上为一个循环,当此时遍历的循环元素小于数组大小时,此时循环次数加一,继续遍历,直到遍历的元素个数大于数组大小,结束循环。取前数组大小的元素个数重新组成新数组返回,为什么去前面大小的元素个数了,因为有可能会重复遍历,所以取钱数组大小的元素个数