228. Summary Ranges
题目描述
Given a sorted integer array without duplicates, return the summary of its ranges.
For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].
这道题目就是把排好序的数组计算它的范围。比如上例就是有[0->2, 4->5, 7]
代码实现
这里是判断是否是差值大于一来决定是否插入范围。用一个bool记录范围是否超过一个数字。这里还需要注意越界的问题。
class Solution {
public:
vector<string> summaryRanges(vector<int>& nums) {
vector<string> res; stringstream ss;
int nlen = nums.size();
bool lst = false;
string tmp;
if(nlen) { ss << nums[0]; tmp = ss.str(); } ss.str("");
long long int t1, t2;
for(int nlen = nums.size(), i = 1, lst = nlen?nums[0]:0; i < nlen; i++) {
t1 = nums[i], t2 = nums[i-1];
// if(nums[i] != nums[i-1] + 1) 这样更好,不需要用到long long
if(t1 - t2 > 1) {
ss << nums[i-1];
if(!lst || i == 1) res.push_back(ss.str());
else res.push_back(tmp+"->"+ss.str());
ss.str("");
ss << nums[i];
tmp = ss.str();
ss.str("");
lst = false;
if(i == nlen - 1) res.push_back(tmp);
}
else {
lst = true;
if(i == nlen - 1) { ss << nums[i]; res.push_back(tmp+"->"+ss.str()); }
}
}
if(nlen == 1) res.push_back(tmp);
return res;
}
};
59. Spiral Matrix II
题目描述
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 ]
]
就是形成nxn的螺旋矩阵。
代码实现
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
int cnt = 1, ttl = n*n, minr = 0, minc = 0, maxr = n, maxc = n;
int row = 0, col = 0;
while(cnt <= ttl) {
while(col < maxc) { res[row][col] = cnt; cnt++; col++; }
row++; col--; minr++;
while(row < maxr) { res[row][col] = cnt; cnt++; row++; }
row--; col--; maxc--;
while(col >= minc) { res[row][col] = cnt; cnt++; col--; }
row--; col++; maxr--;
while(row >= minr) { res[row][col] = cnt; cnt++; row--; }
row++; col++; minc++;
}
return res;
}
};
64. Minimum Path Sum
题目描述
求得最小路径和。
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
代码实现
这里使用的是简单的动态规划的思想。复杂度是O(n^2)。这里计算的是每个节点的大小,如果加上了之前节点的距离比当前的小,那么就更新节点的值。
class Solution {
public:
int minPathSum(vector<vector<int>>& grid) {
int minSum = 0, m = grid.size(), n = m?grid[0].size():0;
if(!m) return 0;
vector<vector<int>> res(m, vector<int>(n, INT_MAX));
for(int i = 0; i < m; i++) {
for(int j = 0; j < n; j++) {
if(i >= 1 || j >= 1) {
if(i >= 1) res[i][j] = grid[i][j] + res[i-1][j];
if(j >= 1) if(res[i][j] > res[i][j-1]+grid[i][j]) res[i][j] = res[i][j-1] + grid[i][j];
}
else res[i][j] = grid[i][j];
}
}
return res[m-1][n-1];
}
};