【算法/贪心算法/区间问题】题解+详细备注(共6题)
class Solution {
public:
bool canJump(vector<int>& nums) {
int n = nums.size();
int maxJump{};
for(int i{};i<n;++i){
maxJump = max(i+nums[i],maxJump);
if(maxJump >= n-1) return true;
if(maxJump < i+1) return false;
}
return false;
}
};
class Solution {
public:
int jump(vector<int>& nums) {
int n = nums.size();
int maxJumps{};
int lastJumps{};
int result{};
for(int i{};i<n;++i){
if(lastJumps >= n-1){
return result;
}
maxJumps = max(maxJumps,i + nums[i]);
if(lastJumps == i){
result++;
lastJumps = maxJumps;
}
}
return result;
}
};
class Solution {
public:
int findMinArrowShots(vector<vector<int>>& points) {
sort(points.begin(),points.end(),[](auto&&a,auto&&b){
return a[0] <= b[0];
});
int result{1};
for(int i = 1;i<points.size();++i){
if(points[i][0] >= points[i-1][0] && points[i][0] <= points[i-1][1]){
points[i][1] = min(points[i-1][1],points[i][1]);
continue;
}
result++;
}
return result;
}
};
class Solution {
public:
int eraseOverlapIntervals(vector<vector<int>>& intervals) {
sort(intervals.begin(),intervals.end(),[](auto&& a,auto&& b){
return a[1] < b[1];
});
int edge = intervals[0][1];
int result{1};
for(int i{};i<intervals.size();++i){
if(edge <= intervals[i][0]){
edge = intervals[i][1];
result++;
}
}
return intervals.size()-result;
}
};
class Solution {
public:
vector<int> partitionLabels(string s) {
int hash[27]{};
for(int i{};i<s.size();++i){
hash[s[i] - 'a'] = i;
}
vector<int> result;
int left{};
int right{};
for(int i{};i<s.size();++i){
right = max(right,hash[s[i]-'a']);
if(i == right){
result.push_back(right-left+1);
left = i+1;
}
}
return result;
}
};
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
sort(intervals.begin(),intervals.end(),[](auto&&a,auto&&b){
return a[0] < b[0];
});
vector<vector<int>> result;
bool flag{false};
for(int i = 1;i<intervals.size();++i){
int start = intervals[i-1][0];
int end = intervals[i-1][1];
while(i < intervals.size() && intervals[i][0] <= end){
end = max(end,intervals[i][1]);
if(i == intervals.size() -1) flag = true;
i++;
}
result.push_back({start,end});
}
if(flag == false){
result.push_back(intervals.back());
}
return result;
}
};
|