第一道
题目名称:59. Spiral Matrix II
题目难度:Medium
题目描述: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 ]
]
题目分析:
这题想不到什么取巧的方法,于是干脆直接手动实现螺旋填值。
思路是在碰到边界的时候顺时针旋转90度,开始新一方向的填值。碰到边界的表示已经填完一整个边(一圈有四个边)了,那么在旋转方向的同时,该边界也需要向内部靠近一个单位。就这样,四周边界“越来越小“,当填充完当前边界的四周之后,开始向更小一个单位的新的边界填值,直至填满。
注意n为0的情况。
最后AC的代码是:
class Solution {
public:
vector<vector<int> > generateMatrix(int n) {
vector<vector<int> > result;
if (n == 0) return result;
int borderTop = 0, borderBottom = n - 1, borderLeft = 0, borderRight = n - 1;
int count = 1, max = n * n;
int temp[n][n];
while (count <= max) {
int tempIndex = borderLeft;
while (tempIndex <= borderRight)
temp[borderTop][tempIndex++] = count++;
tempIndex = borderTop + 1;
borderTop++;
while (tempIndex <= borderBottom)
temp[tempIndex++][borderRight] = count++;
tempIndex = borderRight - 1;
borderRight--;
while (tempIndex >= borderLeft)
temp[borderBottom][tempIndex--] = count++;
tempIndex = borderBottom - 1;
borderBottom--;
while (tempIndex >= borderTop)
temp[tempIndex--][borderLeft] = count++;
borderLeft++;
}
for (int i = 0; i < n; ++i) {
vector<int> tv;
for (int j = 0; j < n; ++j) {
tv.push_back(temp[i][j]);
}
result.push_back(tv);
}
return result;
}
};
第二道
题目名称:34. Search for a Range
题目难度:Medium
题目描述:Given an array of integers sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm’s runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1]
.
For example,
Given [5, 7, 7, 8, 8, 10]
and target value 8,
return [3, 4]
.
题目分析:
O(log n)的时间复杂度要求令人直接联想到了二分查找算法。于是解法的思路非常直接明了,先利用二分查找算法找到其中的一个下标,然后再由这个下标左右扩散开去,即可得出结果。
注意查找不到的情况。
最后AC的代码是:
class Solution {
public:
int binarySearch(vector<int> & nums, int target, int low, int high) {
if (low == high && nums[low] == target) return low;
else if (low >= high) return -1;
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] > target) return binarySearch(nums, target, low, mid);
else return binarySearch(nums, target, mid + 1, high);
}
vector<int> searchRange(vector<int>& nums, int target) {
vector<int> result;
int index = binarySearch(nums, target, 0, nums.size() - 1);
if (index == -1) {
result.push_back(-1);
result.push_back(-1);
return result;
}
int high, low;
high = low = index;
while (low >= 0 && nums[low] == target) low--;
while (high < nums.size() && nums[high] == target) high++;
result.push_back(low + 1);
result.push_back(high - 1);
return result;
}
};