[leetCode刷題筆記]2017.02.09
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)