Arrays分类算法-Spiral Traverse(待完成)

题目要求在这里插入图片描述

corner case:
在这里插入图片描述

解法一:
Iterator解法
Time: O(n) Space: O(n)
代码:

import java.util.*;

class Program {
  public static List<Integer> spiralTraverse(int[][] array) {
    // Write your code here.
		ArrayList<Integer> res = new ArrayList<>();
		if (array == null || array.length == 0 || array[0] == null || array[0].length == 0) {
			return res;
		}
		
		int rowBegin = 0;
		int rowEnd = array.length - 1;
		int colBegin = 0;
		int colEnd = array[0].length - 1;
		
		while (rowBegin <= rowEnd && colBegin <= colEnd) {
			for (int i = colBegin; i <= colEnd; i++) {
				res.add(array[rowBegin][i]);
			}
			rowBegin++;
			
			for (int i = rowBegin; i <= rowEnd; i++) {
				res.add(array[i][colEnd]);
			}
			colEnd--;
			
			if (rowBegin <= rowEnd) {
				for (int i = colEnd; i >= colBegin; i--) {
					res.add(array[rowEnd][i]);
				}
			}
			rowEnd--;
			
			if (colBegin <= colEnd) {
				for (int i = rowEnd; i >= rowBegin; i--) {
					res.add(array[i][colBegin]);
				}
			}
			colBegin++;		
		}			
		return res;
  }
}

解法二:
recursive解法
Time: O(n) Space: O(n)
代码:


已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页