摘要:注意兩點(diǎn)兩個(gè)循環(huán)必須是先走斜上的循環(huán),再走斜下的循環(huán)兩個(gè)循環(huán)之后的平移操作,有著嚴(yán)格的相對順序斜上之后的平移,先考慮右移,再考慮下移斜下之后的平移,先考慮下移,再考慮右移。
Problem
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.
ExampleGiven a matrix:
[ [1, 2, 3, 4], [5, 6, 7, 8], [9,10, 11, 12] ]
return [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]
NoteZ字形走法,從左下到右上,右移或下移一位,再從右上到左下,下移或右移一位,如此往復(fù)。
注意兩點(diǎn):
兩個(gè)while循環(huán)必須是先走斜上的循環(huán),再走斜下的循環(huán);
兩個(gè)while循環(huán)之后的平移操作,有著嚴(yán)格的相對順序:斜上之后的平移,先考慮右移,再考慮下移;斜下之后的平移,先考慮下移,再考慮右移。
Solutionpublic class Solution { public int[] printZMatrix(int[][] matrix) { if (matrix == null) return null; int m = matrix.length, n = matrix[0].length, count = m * n; int[] res = new int[count]; res[0] = matrix[0][0]; int i = 1, r = 0, c = 0; while (i < count) { while (r-1 >= 0 && c+1 < n) res[i++] = matrix[--r][++c]; if (c+1 < n) res[i++] = matrix[r][++c]; else if (r+1 < m) res[i++] = matrix[++r][c]; while (r+1 < m && c-1 >= 0) res[i++] = matrix[++r][--c]; if (r+1 < m) res[i++] = matrix[++r][c]; else if (c+1 < n) res[i++] = matrix[r][++c]; } return res; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/yun/65659.html
Problem Given a binary tree, return the zigzag level order traversal of its nodes values. (ie, from left to right, then right to left for the next level and alternate between). Example Given binary tr...
摘要:棧迭代復(fù)雜度時(shí)間空間遞歸??臻g對于二叉樹思路用迭代法做深度優(yōu)先搜索的技巧就是使用一個(gè)顯式聲明的存儲遍歷到節(jié)點(diǎn),替代遞歸中的進(jìn)程棧,實(shí)際上空間復(fù)雜度還是一樣的。對于先序遍歷,我們出棧頂節(jié)點(diǎn),記錄它的值,然后將它的左右子節(jié)點(diǎn)入棧,以此類推。 Binary Tree Preorder Traversal Given a binary tree, return the preorder tr...
摘要:有效三角形的個(gè)數(shù)雙指針最暴力的方法應(yīng)該是三重循環(huán)枚舉三個(gè)數(shù)字。總結(jié)本題和三數(shù)之和很像,都是三個(gè)數(shù)加和為某一個(gè)值。所以我們可以使用歸并排序來解決這個(gè)問題。注意因?yàn)闅w并排序需要遞歸,所以空間復(fù)雜度為 ...
摘要:方法直接查找數(shù)組的位的迭代器,調(diào)用方法得到的整數(shù)即為要返回的元素。再寫迭代器的方法返回指針元素的并讓指針通過遞歸方法指向下一個(gè)元素。 Zigzag Iterator Problem Given two 1d vectors, implement an iterator to return their elements alternately. Example Given two 1d ...
摘要:遞歸法不說了,棧迭代的函數(shù)是利用的原理,從根節(jié)點(diǎn)到最底層的左子樹,依次入堆棧。然后將出的結(jié)點(diǎn)值存入數(shù)組,并對出的結(jié)點(diǎn)的右子樹用函數(shù)繼續(xù)迭代。 Problem Given a binary tree, return the inorder traversal of its nodes values. Example Given binary tree {1,#,2,3}, 1 ...
閱讀 601·2023-04-26 02:59
閱讀 718·2023-04-25 16:02
閱讀 2195·2021-08-05 09:55
閱讀 3634·2019-08-30 15:55
閱讀 4736·2019-08-30 15:44
閱讀 1823·2019-08-30 13:02
閱讀 2228·2019-08-29 16:57
閱讀 2316·2019-08-26 13:35