题目来源:力扣《剑指Offer》第二版
完成时间:2022/07/25
11. 旋转数组的最小数字
我的题解
这道题坑有点多,因为会有几种特殊情况,我一开始没有思路,看书上的代码敲的,不够简洁。
class Solution {
public:
int minArray(vector<int>& numbers) {
int right = numbers.size() - 1,left = 0,mid = left;
while(numbers[left] >= numbers[right]) {
if(right - left == 1){
mid = right;
break;
}
mid = left + (right - left) / 2;
//如果三者相同,则只能通过顺序查找
if(numbers[mid] == numbers[right] && numbers[mid] == numbers[left]){
return minInOrder(left,right,numbers);
}
if(numbers[mid] >= numbers[right]) {
left = mid;
}else if(numbers[mid] <= numbers[right]){
right = mid;
}
}
return numbers[mid];
}
//顺序查找
int minInOrder(int left,int right,vector<int>& numbers) {
int min = numbers[left];
for(int i = 0;i < right;i++) {
if(numbers[i] < min){
min = numbers[i];
}
}
return min;
}
};
13. 机器人的运动范围
我的题解
这道题用深搜就可以解决了
class Solution {
public:
//检查格子是否能进入
bool check(int x,int y,int k,int m,int n,vector<vector<int>>& myMap) {
if(x > m-1 || y > n-1 || x < 0 || y < 0 || myMap[x][y] == 1){
return false;
}
int result = 0;
while(x > 0) {
result += x % 10;
x /= 10;
}
while(y > 0) {
result += y % 10;
y /= 10;
}
return result <= k;
}
int dfs(int m,int n,int x,int y,int k,vector<vector<int>>& myMap) {
int count = 0;
if(check(x,y,k,m,n,myMap)){
myMap[x][y] = 1;
count = 1;
count += dfs(m,n,x+1,y,k,myMap);
count += dfs(m,n,x-1,y,k,myMap);
count += dfs(m,n,x,y+1,k,myMap);
count += dfs(m,n,x,y-1,k,myMap);
}
return count;
}
int movingCount(int m, int n, int k) {
vector<vector<int>> myMap(m);
for(int i= 0;i < m;i++){
myMap[i].resize(n);
}
return dfs(m,n,0,0,k,myMap);
}
};