辣條走起续室,每個(gè)月的刷題99元獎(jiǎng)勵(lì)靠大家了
前言
今天的題目
每天的題目見(jiàn)github(看最新的日期):
https://github.com/gzc426
具體的題目可以去诺徘茫客網(wǎng)對(duì)應(yīng)專題去找。
昨天的題解
題目
每天一道劍指offer-順時(shí)針打印矩陣
來(lái)源:牛客網(wǎng)對(duì)應(yīng)專題
題目詳述
輸入一個(gè)矩陣,按照從外向里以順時(shí)針的順序依次打印出每一個(gè)數(shù)字,例如腻异,如果輸入如下4 X 4矩陣: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 則依次打印出數(shù)字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
題目詳解
思路
按照順時(shí)針打印矩陣,這里的話我用了一個(gè)變量count,來(lái)記錄遍歷的數(shù)目这揣,當(dāng)count如果小于等于二維矩陣的數(shù)目的話悔常,說(shuō)明沒(méi)有遍歷完成,直到count達(dá)到二維數(shù)組的數(shù)目给赞。
代碼中的left,right,bottom,top解讀机打。left代表最左的一層,top代表最頂?shù)囊粚悠福琤ottom代表最低的一層残邀,right代表最右的一層,舉個(gè)例子柑蛇,比如最頂?shù)膶觮op芥挣,每當(dāng)遍歷完最上面的一層,那么就top++耻台,比如最底層bottom每當(dāng)遍歷完最低一層就bottom--空免,這樣下去肯定會(huì)出現(xiàn)top和bottom相遇的情況,也就是全部都遍歷完了
代碼
import java.util.ArrayList;
public class Solution {
? ?public ArrayList<Integer> printMatrix(int [][] matrix) {
? ? ? ?ArrayList<Integer> resultList = new ArrayList<>();
? ? ? ?int cols = matrix[0].length;
? ? ? ?int rows = matrix.length; ? ?
? ? ? ?int left=0,top=0,bottom=rows-1,right=cols-1;
? ? ? ?int count = 0;//計(jì)數(shù)盆耽,count如果達(dá)到數(shù)組的全部個(gè)數(shù)蹋砚,那么結(jié)束。
? ? ? ?while(count < cols*rows)
? ? ? ?{
? ? ? ? ? ?for(int i=left;i<=right;i++)//從左往右進(jìn)行遍歷征字,第一層
? ? ? ? ? ?{//left是目前最左邊的那個(gè)邊界都弹,right是目前最右邊的邊界
? ? ? ? ? ? ? ?resultList.add(matrix[top][i]);
? ? ? ? ? ? ? ?count++;
? ? ? ? ? ? ? ?if(count >= cols*rows)
? ? ? ? ? ? ? ? ? ?return resultList;
? ? ? ? ? ?}
? ? ? ? ? ?top++;//遍歷完目前的最頂層娇豫,那么top就到下一層
? ? ? ? ? ?for(int i=top;i<=bottom;i++)
? ? ? ? ? ?{//從上往下進(jìn)行遍歷匙姜,top是目前最上的邊界,bottom是目前最下的邊界
? ? ? ? ? ? ? ?resultList.add(matrix[i][right]);
? ? ? ? ? ? ? ?count++;
? ? ? ? ? ? ? ?if(count >= cols*rows)
? ? ? ? ? ? ? ? ? ?return resultList;
? ? ? ? ? ?}
? ? ? ? ? ?right--;//遍歷完最右邊的邊界冯痢,那么right就減一氮昧,到下一個(gè)最右邊邊界
? ? ? ? ? ?for(int i=right;i>=left;i--)
? ? ? ? ? ?{//從右到左防症,和上面同理
? ? ? ? ? ? ? ?resultList.add(matrix[bottom][i]);
? ? ? ? ? ? ? ?count++;
? ? ? ? ? ? ? ?if(count >= cols*rows)
? ? ? ? ? ? ? ? ? ?return resultList;
? ? ? ? ? ?}
? ? ? ? ? ?bottom--;
? ? ? ? ? ?for(int i=bottom;i>=top;i--)
? ? ? ? ? ?{//從下到上曹铃,和上面同理。
? ? ? ? ? ? ? ?resultList.add(matrix[i][left]);
? ? ? ? ? ? ? ?count++;
? ? ? ? ? ? ? ?if(count >= cols*rows)
? ? ? ? ? ? ? ? ? ?return resultList;
? ? ? ? ? ?}
? ? ? ? ? ?left++;
? ? ? ?}
? ? ? ?return resultList;
? ?}
}
代碼截圖(避免亂碼)
結(jié)束語(yǔ)
作者喬戈里親歷2019秋招,哈工大計(jì)算機(jī)本碩尤误,百度java工程師,歡迎大家關(guān)注我的微信公眾號(hào):程序員喬戈里丹拯,公眾號(hào)有3T編程資源赶盔,以及我和我朋友(百度C++工程師)在秋招期間整理的近200M的面試必考的java與C++面經(jīng),并有每天一道leetcode打卡群與技術(shù)交流群寸癌,歡迎關(guān)注专筷。