题解 | #逆时针吃草#
逆时针吃草
https://www.nowcoder.com/practice/9eaf6e983ec042f7b952a65b46486f8e?tpId=363&tqId=10614188&ru=/exam/oj&qru=/ta/super-company23Year/question-ranking&sourceUrl=%2Fexam%2Foj%3Fpage%3D1%26tab%3D%25E7%25AE%2597%25E6%25B3%2595%25E7%25AF%2587%26topicId%3D363
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param matrix int整型二维数组 * @return int整型一维数组 */ public int[] eatGrass (int[][] matrix) { // 左边界 int left = 0; // 右边界 int right = matrix[0].length - 1; // 上边界 int top = 0; // 下边界 int bottom = matrix.length - 1; ArrayList<Integer> arrayList = new ArrayList<>(); // 当左边界小于等于右边界并且上边界小于等于下边界 while (left <= right && top <= bottom) { // 先输出最左边一类 比如 4,1 for (int i = bottom; i >= top; i--) { arrayList.add(matrix[i][left]); } left++; // 再添加最上面一行,比如 2,3 for (int i = left; i <= right ; i++) { arrayList.add(matrix[top][i]); } top++; // 再添加最右边一列,比如 5 for (int i = top; i <= bottom && left <= right ; i++) { arrayList.add(matrix[top][right]); } right--; // 最后添加下面一行,比如6 for (int i = right; i >= left && top <= bottom ; i--) { arrayList.add(matrix[bottom][i]); } bottom--; } // 集合转数组进行返回 int [] result = new int[arrayList.size()]; for (int i = 0; i < arrayList.size(); i++) { result[i] = arrayList.get(i); } return result; } }
本题知识点分析:
1.矩阵顺时针遍历(题干给错!测试用例都是按左下角开始然后顺时针遍历,题干说逆时针)
2.数组遍历
3.集合存取
4.集合转数组
本题解题思路分析:
1.只要明确边界问题,然后就是数学模拟了
2.注意下标越界即可,在left和top发生变化后,下面的循环条件就需要进行增加
3.可以直接创建一个数组,然后给数组赋值,我习惯先创建集合,这样适用于元素个数未知的情况,当然本题是知道的,就是矩阵元素个数
本题使用编程语言: Java
如果你觉得本篇文章对你有帮助的话,可以点个赞,支持一下,感谢~