目录
3 模拟法
模拟法,顾名思义,就是利用计算机模拟问题的求解过程,从而得到问题的解。模拟法由于简单,因此又被称为“不是算法的算法”。模拟法是学习算法的基础,通过模拟可以学习编程的各类技巧,提升初学者建立各种编程逻辑模型的感觉。大部分模拟题目 直接模拟就可以求解,还有少量模拟题目需要考生简化模拟过程,否则可能会使逻辑复杂,导致求解用时过长。模拟法适用于问题求解清晰、运算规模较小的问题。如果问题求解的时空代价很大,就要考虑是否有其他更好的解决方案。
【题1】LeetCode258:各位相加
给定一个非负整数 num
,反复将各个位上的数字相加,直到结果为一位数。返回这个结果。
示例 :
输入: num = 38
输出: 2
解释: 各位相加的过程为:(38 --> 3 + 8 --> 11)(11 --> 1 + 1 --> 2) 由于 2
是一位数,所以返回 2。
题解:
class Solution {
public:
int addDigits(int num) {
int a,b;
while(num>=10)
{
a = num/10;
b = num%10;
num = a+b;
}
return num;
}
};
【题2】LeetCode54:螺旋矩阵
给你一个 m
行 n
列的矩阵 matrix
,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
提示:
m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
题解:
可以将矩阵看成若干层,首先输出最外层的元素,其次输出次外层的元素,直到输出最内层的元素。
定义矩阵的第 k层是到最近边界距离为 k的所有顶点。例如,下图矩阵最外层元素都是第 1 层,次外层元素都是第 2 层,剩下的元素都是第 3 层。
[[1, 1, 1, 1, 1, 1, 1],
[1, 2, 2, 2, 2, 2, 1],
[1, 2, 3, 3, 3, 2, 1],
[1, 2, 2, 2, 2, 2, 1],
[1, 1, 1, 1, 1, 1, 1]]
对于每层,从左上方开始以顺时针的顺序遍历所有元素。假设当前层的左上角位于(top,left),右下角位于 (bottom,right),按照如下顺序遍历当前层的元素。
从左到右遍历上侧元素,依次为 (top,left) 到 (top,right)。
从上到下遍历右侧元素,依次为 (top+1,right) 到 (bottom,right)。
如果 left<right且 top<bottom,则从右到左遍历下侧元素,依次为 (bottom,right−1)到 (bottom,left+1),以及从下到上遍历左侧元素,依次为 (bottom,left)到 (top+1,left)。
遍历完当前层的元素之后,将 left 分别增加 1,将 right 和 bottom 分别减少 1,进入下一层继续遍历,直到遍历完所有元素为止。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int rows = matrix.size(), columns = matrix[0].size();
vector<int> order;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom) {
for (int column = left; column <= right; column++) {
order.push_back(matrix[top][column]);
}
for (int row = top + 1; row <= bottom; row++) {
order.push_back(matrix[row][right]);
}
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
order.push_back(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
order.push_back(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return order;
}
};