Heap Greedy
1 239 Sliding Window Maximun 双端队列
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public int[] maxSlidingWindow(int[] nums, int k) { if (nums == null || k <= 0) return new int[0]; int n = nums.length; int[] r = new int[n - k + 1]; int ri = 0; Deque<Integer> q = new ArrayDeque<>(); for (int i = 0; i < nums.length; i++) { while (!q.isEmpty() && q.peek() < i - k + 1){ q.poll(); } while (!q.isEmpty() && nums[q.peekLast()] < nums[i]) { q.pollLast(); } q.offer(i); if (i >= k - 1) { r[ri++] = nums[q.peek()]; } } return r; }
2 134 Gas Station 比较用的和有的,两个结论
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public int canCompleteCircuit(int[] gas, int[] cost) { if(gas==null || gas.length==0 || cost==null || cost.length==0 || gas.length!=cost.length) return -1; int total = 0, sum = 0, point = -1; for (int i = 0; i < gas.length; i++) { int diff = gas[i] - cost[i]; total += diff; sum += diff; if (sum < 0){ sum = 0; point = i; } } return total >= 0 ? point + 1: -1; }
3 135 Candy
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public int candy(int[] ratings) { int[] candys = new int[ratings.length]; Arrays.fill(candys, 1); for (int i = 1; i < ratings.length; i++) { if (ratings[i] > ratings[i-1]) candys[i] = candys[i - 1] + 1; } for (int i = ratings.length - 2; i >= 0; i--) { if (ratings[i] > ratings[i+1]) candys[i] = Math.max(candys[i], candys[i + 1] + 1); } int res = 0; for(int i : candys) { res += i; } return res; }