【leetcode】Array——Spiral MatrixII(59)
2016-02-11 22:43
435 查看
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
继承上一道题目的思路:
使用while true 循环,在里面给四个边界进行判断
代码:
int[][]result =
new int[n][n];
if(n==0)
return result;
int count =1;
int top=0;int button=n-1;int right=n-1;int left=0;
while(true){
if(top>button||left>right)
break;
for(int i=left;i<=right;i++,count++){
result[top][i]=count;
}
top++;
if(top>button||left>right)
break;
for(int i=top;i<=button;i++,count++)
result[i][right]=count;
right--;
for(int i=right;i>=left;i--,count++)
result[button][i]=count;
button--;
if(top>button||left>right)
break;
for(inti =button;i>=top;i--,count++)
result[i][left]=count;
left++;
}
return result;
改进思路:其实内部并不需要进行边界判断,因为n确定之后,循环的次数肯定是n*n次,所以只需要
while(count<=n*n)即可。
For example,
Given n = 3,
You should return the following matrix:
[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]
继承上一道题目的思路:
使用while true 循环,在里面给四个边界进行判断
代码:
int[][]result =
new int[n][n];
if(n==0)
return result;
int count =1;
int top=0;int button=n-1;int right=n-1;int left=0;
while(true){
if(top>button||left>right)
break;
for(int i=left;i<=right;i++,count++){
result[top][i]=count;
}
top++;
if(top>button||left>right)
break;
for(int i=top;i<=button;i++,count++)
result[i][right]=count;
right--;
for(int i=right;i>=left;i--,count++)
result[button][i]=count;
button--;
if(top>button||left>right)
break;
for(inti =button;i>=top;i--,count++)
result[i][left]=count;
left++;
}
return result;
改进思路:其实内部并不需要进行边界判断,因为n确定之后,循环的次数肯定是n*n次,所以只需要
while(count<=n*n)即可。
相关文章推荐
- HDU 1712(分组背包)
- 【leetcode】Array——Search Insert Position(35)
- Atitit.php opcode虚拟机指令集 分类以及详细解释
- 如何下载xcode官方开发文档
- 【leetcode】Array——Spiral Matrix(54)
- 【leetcode】Array—— Set Matrix Zeroes(73)
- GitHub入门与实践(1)GitHub 前期准备
- 分页机制
- 【leetcode】Array——Sort Color(75)
- 【leetcode】Array——SubsetsII(90)
- 如何创建.gitignore文件
- 【leetcode】Array——Subsets(78)
- 118. Pascal's Triangle LeetCode
- 【leetcode】Array——Trapping Rain Water(42)
- 【leetcode】Array——Triangle(120)
- 【leetcode】Array——Unique Paths II(63)
- 华为机试题:可怕的阶乘
- java常见问题
- 66. Plus One LeetCode
- Java—设计模式(工厂模式)