452. 用数量最少的箭引爆气球
题目:452. 用最少数量的箭引爆气球 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
先排序再计算重叠区域?
一遍过,开心
solution
public class Solution {
public int FindMinArrowShots(int[][] points) {
var sortedpoints = points.OrderBy(p => p[0]).ToList();
int left = sortedpoints[0][0];
int right = sortedpoints[0][1];
int count = 1;
for(int i = 1; i < sortedpoints.Count; i ++)
{
if(sortedpoints[i][0] > right)
{
count ++;
left = sortedpoints[i][0];
right = sortedpoints[i][1];
}
else
{
left = sortedpoints[i][0];
right = sortedpoints[i][1] < right ? sortedpoints[i][1] : right;
}
}
return count;
}
}
summary
435. 无重叠区间
题目:435. 无重叠区间 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
重叠的时候怎样移除可以使覆盖范围尽可能小
solution
public class Solution {
public int EraseOverlapIntervals(int[][] intervals) {
Array.Sort(intervals,(a, b) => a[0].CompareTo(b[0]));
int result = 0;
for(int i = 1; i < intervals.Length; i ++)
{
if(intervals[i][0] < intervals[i - 1][1])
{
result ++;
intervals[i][1] = intervals[i][1] < intervals[i - 1][1] ? intervals[i][1] : intervals[i - 1][1];
}
}
return result;
}
}
summary
key:
理解是否重叠只和当前区域的左边界与上一区域的右边界的关系有关
763. 划分字母区间
题目:763. 划分字母区间 - 力扣(LeetCode)
题解:代码随想录 (programmercarl.com)
隐藏的重叠区间问题
solution
public class Solution
{
public IList<int> PartitionLabels(string s)
{
StringBuilder sb = new StringBuilder(s);
Dictionary<char, int> table = getTable(sb);
List<int> result = new List<int>();
int left = 0;
int right = 0;
for(int i = 0; i < sb.Length; i ++)
{
if(i <= right) right = table[sb[i]] > right ? table[sb[i]] : right;
else
{
result.Add(right - left + 1);
left = i;
right = table[sb[i]];
}
}
result.Add(right - left + 1);
return result;
}
public Dictionary<char, int> getTable(StringBuilder sb)
{
Dictionary<char, int> table = new Dictionary<char,int>();
for(int i = 0; i < sb.Length; i ++)
{
table[sb[i]] = i;
}
return table;
}
}
优化写法
public class Solution
{
public IList<int> PartitionLabels(string s)
{
var lastIndex = new Dictionary<char, int>();
for (int i = 0; i < s.Length; i++)
{
lastIndex[s[i]] = i;
}
var result = new List<int>();
int start = 0, end = 0;
for (int i = 0; i < s.Length; i++)
{
end = Math.Max(end, lastIndex[s[i]]);
if (i == end)
{
result.Add(end - start + 1);
start = i + 1;
}
}
return result;
}
}
summary
错误:
又出现了最后一个元素未加入结果的问题,学习优化的写法
其实每个遍历右边界都在更新,不要拆分去看,关键点是遍历指针追上右边界的时刻