54. Spiral Matrix
这个思想是用whille循环套四个并排的for循环,模拟螺旋走势。注意循环结束要将下次循环的上限减少。
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) {List<Integer> res = new ArrayList<Integer>();
if (matrix.length == 0) {
return res;
}
int rowBegin = 0;
int rowEnd = matrix.length-1;
int colBegin = 0;
int colEnd = matrix[0].length - 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
// Traverse Right
for (int j = colBegin; j <= colEnd; j ++) {
res.add(matrix[rowBegin][j]);
}
rowBegin++;
// Traverse Down
for (int j = rowBegin; j <= rowEnd; j ++) {
res.add(matrix[j][colEnd]);
}
colEnd--;
if (rowBegin <= rowEnd) {
// Traverse Left
for (int j = colEnd; j >= colBegin; j --) {
res.add(matrix[rowEnd][j]);
}
}
rowEnd--;
if (colBegin <= colEnd) {
// Traver Up
for (int j = rowEnd; j >= rowBegin; j --) {
res.add(matrix[j][colBegin]);
}
}
colBegin ++;
}
return res;
}
}
55. Jump Game
这道题其实可以用很简单的方法做出来(O(n),O(1)),如果游戏最后可以跳到最后一个点,那么只要找出来可以跳到的最远距离,如果最远距离等于或者大于最后一个点,那么一i定是true
public class Solution {
public boolean canJump(int[] nums) {
// initial point
int reach = 1;
for (int i = 0; i < reach && reach < nums.length; i++) {
reach = Math.max(reach, 1 + i + nums[i]);
}
return reach >= nums.length;
}
}
45. Jump Game II
这道题是上一题的升级版。其实用暴力破解法,while循环往前跑,里面嵌套一个循环找到下个能跑最远的index
public class Solution {
public int jump(int[] nums) {
if (nums.length <= 1) {
return 0;
}
if (nums[0] == 0) {
return -1;
}
// current max index can reach
int maxCover = nums[0];
int steps = 0, start = 0;
while (start < nums.length && start <= maxCover) {
++steps;
// when approach the last point
if (maxCover >= nums.length - 1) {
return steps;
}
int nextMax = 0;
for (int i = start; i <= maxCover; i++) {
if (i + nums[i] > nextMax) {
nextMax = i + nums[i];
start = i;
}
}
maxCover = nextMax;
}
return -1;
}
}
56. Merge Intervals
之前一直没有用过interval这玩意,直接看答案了:
http://blog.csdn.net/zdavb/article/details/47252657
先根据所有interval的起始点进行排序,然后拿输出队列的顶部与inrervals当前元素进行比较,并修改输出队列(修改interval或者添加新的interval)