题源:LeetCode
1706. 球会落何处
class Solution {
public:
vector<int> findBall(vector<vector<int>>& grid) {
int n = grid[0].size();
vector<int> ans(n, -1);
for(int j = 0; j < n; j++){
int col = j;
for(auto &row : grid){
int dir = row[col];
col += dir;
if(col < 0 || col == n || row[col] != dir){
col = -1;
break;
}
}
if(col >= 0)
ans[j] = col;
}
return ans;
}
};
2016. 增量元素之间的最大差值
思路:遍历一遍,边比较边记录前缀最小值和答案。
class Solution {
public:
int maximumDifference(vector<int>& nums) {
int n = nums.size();
int ans = -1, premin = nums[0];
for(int i = 1; i < n; i++){
if(nums[i] > premin){
ans = max(ans, nums[i] - premin);
}else{
premin = nums[i];
}
}
return ans;
}
};
|