保证每次操作都是局部最优的,并且最后得到的结果是全局最优的。
1. 分配饼干
455. Assign Cookies (Easy)
class Solution { public int findContentChildren(int[] g, int[] s) { if(g.length == 0 || s.length ==0){ return 0; } Arrays.sort(g); Arrays.sort(s); int num = 0; int i=0; int j=0; while(i<g.length && j < s.length){ if(g[i] <= s[j]){ num++; i++; j++; }else{ j++; } } return num; } }
2. 不重叠的区间个数
435. Non-overlapping Intervals (Medium)
class Solution { public int eraseOverlapIntervals(int[][] intervals) { if(intervals.length == 0){ return 0; } Arrays.sort(intervals,Comparator.comparingInt(o -> o[1])); int cnt = 1; int end = intervals[0][1]; for(int i=1; i < intervals.length; i++){ if(intervals[i][0] < end){ continue; } end = intervals[i][1]; cnt++; } return intervals.length - cnt; } }
3. 投飞镖刺破气球
452. Minimum Number of Arrows to Burst Balloons (Medium)
题目描述:气球在一个水平数轴上摆放,可以重叠,飞镖垂直投向坐标轴,使得路径上的气球都被刺破。求解最小的投飞镖次数使所有气球都被刺破。
也是计算不重叠的区间个数,不过和 Non-overlapping Intervals 的区别在于,[1, 2] 和 [2, 3] 在本题中算是重叠区间。
class Solution { public int findMinArrowShots(int[][] points) { if (points.length == 0) { return 0; } Arrays.sort(points, Comparator.comparingInt(o -> o[1])); int cnt = 1, end = points[0][1]; for (int i = 1; i < points.length; i++) { if (points[i][0] <= end) { continue; } cnt++; end = points[i][1]; } return cnt; } }