Implement pow(x, n).
解题思路:
1. 题目要求实现 x 的 n 次幂,原理其实很简单,直接n个x连乘即可,但是肯定会超时,所以需要考虑效率更高的算法
2. 所考虑用分治的思想来解决问题:pow(x,n) = pow(x,n/2) ^2
3. 需要考虑n为负数的情况,同时如果直接用pow(x,n/2) * pow(x,n/2)这样表示的话,还是会计算两次,仍然耗时,所以可以考虑用一个temp来记录pow(x,n/2)的值,这样函数只需要调用一次,速度会更快
代码如下:
public class Solution {
public double myPow(double x, int n) {
if(n == 0){
return 1;
}
double temp = myPow(x,n/2);
if(n % 2 == 0){
return temp*temp;
}else{
if(n > 0){
return x*temp*temp;
}else{
return temp*temp/x;
}
}
}
}
Problem 54 Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]
You should return [1,2,3,6,9,8,7,4,5]
.
1. 题目要求螺旋式地顺时针遍历矩阵,我们可以先简后繁的考虑一下问题:如何遍历矩阵的最外面的一圈
2. 上,右,下,左,遍历完最外面一圈后,可以把矩阵剩下的部分当成一个新的矩阵,再重新遍历它最外面的一圈
3. 如此循环递归,既可以遍历完整个矩阵
4. 需要考虑的边界情况是当矩阵只有一行或者一列的时候,只需遍历上右,无需再遍历下左,否则会重复遍历。
代码如下:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> result = new ArrayList<>();
int row = matrix.length;
if(row == 0){
return result;
}
int col = matrix[0].length;
visit(matrix,col,row,0,0,result);
return result;
}
public void visit(int[][] matrix, int col, int row, int x, int y, List<Integer> result){
int tempX = x;
int tempY = y;
if(col <= 0 || row <= 0){
return;
}
//up
for(int i = y;i < y+col;i++){
result.add(matrix[tempX][i]);
tempY = i;
//System.out.println(tempX +","+tempY);
}
//right
for(int i = x+1;i < x+row;i++){
result.add(matrix[i][tempY]);
tempX = i;
//System.out.println(tempX +","+tempY);
}
//down
if(row != 1){
for(int i = tempY -1;i >= y;i--){
result.add(matrix[tempX][i]);
tempY = i;
//System.out.println(tempX +","+tempY);
}
}
//left
if(col != 1){
for(int i = tempX-1;i > x;i--){
result.add(matrix[i][tempY]);
tempX = i;
//System.out.println(tempX +","+tempY);
}
}
visit(matrix,col-2,row-2,tempX,tempY+1,result);
}
}