435. 无重叠区间
先根据start排序,然后判断:如果前一个的end小于等于后一个的start,不需要删除;否则删除end较大的一个,然后剩余的end赋值较小的
1 class Solution { 2 public: 3 static bool comp(const vector<int>& a, const vector<int>& b){ 4 return a[0] < b[0]; 5 } 6 int eraseOverlapIntervals(vector<vector<int>>& intervals) { 7 if(intervals.size() == 0) return 0; 8 sort(intervals.begin(),intervals.end(),comp); 9 int result = 0; 10 for(int i = 1; i < intervals.size(); i++){ 11 if(intervals[i][0] >= intervals[i-1][1]) continue; 12 result++; 13 intervals[i][1] = min(intervals[i][1],intervals[i-1][1]); 14 } 15 return result; 16 } 17 };
先统计每个字母最后出现的位置,然后遍历字符串,当当前的字符是最后位置时,push进集合,同时开始端+1
1 class Solution { 2 public: 3 vector<int> partitionLabels(string s) { 4 int hash[26]; 5 for(int i = 0; i < s.size(); i++){ 6 hash[s[i]-'a'] = i; 7 } 8 vector<int> result; 9 int start = 0; 10 int end = 0; 11 for(int i = 0; i < s.size(); i++){ 12 end = max(end,hash[s[i]-'a']); 13 if(end == i){ 14 result.push_back(end-start+1); 15 start = i+1; 16 } 17 } 18 return result; 19 } 20 };
1 class Solution { 2 public: 3 static bool comp(const vector<int>& a, const vector<int>& b){ 4 return a[0] < b[0]; 5 } 6 vector<vector<int>> merge(vector<vector<int>>& intervals) { 7 vector<vector<int>> result; 8 sort(intervals.begin(),intervals.end(),comp); 9 result.push_back(intervals[0]); 10 for(int i = 1; i < intervals.size(); i++){ 11 if(result.back()[1] < intervals[i][0]){ 12 result.push_back(intervals[i]); 13 continue; 14 } 15 result.back()[1] = max(result.back()[1],intervals[i][1]); 16 } 17 return result; 18 } 19 };