Leetcode solution to a problem - greedy algorithm thought Thought

1. Assign biscuits

Ensure that each operation is a local optimum, and the final result is a global optimum.

1. Assign biscuits

455. Assign Cookies (Easy)

Input: [1,2], [1,2,3]
Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

Topic Description: Every child has a satisfaction, each cookie has a size, only the size of the biscuit greater than or equal satisfaction of a child, the child will be met. Solving maximum number of children can be met.

Give a child the cookie should be as small as possible but also to meet the children, will be able to bring such a large biscuit relatively large degree to meet the children. Because the youngest child most likely to be met, we first meet the youngest child.

Proof: Suppose in a particular selection, select greedy strategy to meet the current allocation of the youngest child of the m-th cookies, crackers m-th to meet the child's minimum biscuits. Suppose there is a optimal strategy, assigned to the n-th child biscuits, and m <n. We can see that after this round of distribution, the allocation of the remaining biscuits greedy strategy must have a far greater than the optimal strategy. Therefore, in the subsequent distribution, greedy strategy will be able to meet more children. That is better than the greedy strategy policy does not exist, that greedy strategy is the optimal strategy.

public int findContentChildren(int[] g, int[] s) {
    Arrays.sort(g); Arrays.sort(s); int gi = 0, si = 0; while (gi < g.length && si < s.length) { if (g[gi] <= s[si]) { gi++; } si++; } return gi; }

2. The number of sections do not overlap

435. Non-overlapping Intervals (Medium)

Input: [ [1,2], [1,2], [1,2] ]

Output: 2

Explanation: You need to remove two [1,2] to make the rest of intervals non-overlapping.
Input: [ [1,2], [2,3] ]

Output: 0

Explanation: You don't need to remove any of the intervals since they're already non-overlapping.

Description Title: calculating a set interval so as not to overlap the number of intervals to be removed.

Calculating the number does not overlap the first section up to the composition, and then subtracting the number of intervals do not overlap with the total number of intervals.

In each selection, the most important of the end of the interval, the lower end of the selected interval, the greater the range of space left behind, then be able to select the number of sections behind the greater.

Sorting carried out in the end section, the end of each time selecting a minimum, and a front section and not to overlap interval.

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; }

Use a lambda expression to create Comparator will lead algorithm running time is too long, if you focus on running time, it can be modified to create Comparator general statement:

Arrays.sort(intervals, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) { return o1[1] - o2[1]; } });

3. darts punctured balloon

452. Minimum Number of Arrows to Burst Balloons (Medium)

Input:
[[10,16], [2,8], [1,6], [7,12]]

Output:
2

Description Title: balloon placed in a number of horizontal axis, may overlap, darts toward the vertical axis, such that the balloon on the path are punctured. Solving the minimum number of darts that all balloons are punctured.

Also count the number of sections do not overlap, however, and Non-overlapping Intervals difference is that [1, 2] and [2, 3] be overlapping ranges In this problem.

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; }

The height and number reassembly queue

406. Queue Reconstruction by Height(Medium)

Input:
[[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]

Output:
[[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]

Description Title: a student two components (H, k) is described, h represents the height, k is the k has a top surface higher than the height of the student and his or as high as him.

In order to insert operation does not affect subsequent operations, higher student should first insertion height, height or smaller student originally inserted correctly k-th position may become the first k + 1 positions.

Descending height h, k number of values ​​in ascending order, and then inserted into a student k-th position in the queue.

public int[][] reconstructQueue(int[][] people) {
    if (people == null || people.length == 0 || people[0].length == 0) { return new int[0][0]; } Arrays.sort(people, (a, b) -> (a[0] == b[0] ? a[1] - b[1] : b[0] - a[0])); List<int[]> queue = new ArrayList<>(); for (int[] p : people) { queue.add(p[1], p); } return queue.toArray(new int[queue.size()][]); }

The buying and selling stocks maximum benefit

121. Best Time to Buy and Sell Stock (Easy)

Subject description: a stock transaction includes buying and selling, trading only once, seeking the maximum benefit.

As long as the previous record minimum price, the minimum price as the purchase price and the current price as the sale price, see current earnings is not the biggest gains.

public int maxProfit(int[] prices) {
    int n = prices.length; if (n == 0) return 0; int soFarMin = prices[0]; int max = 0; for (int i = 1; i < n; i++) { if (soFarMin > prices[i]) soFarMin = prices[i]; else max = Math.max(max, prices[i] - soFarMin); } return max; }

6. buying and selling stocks maximum benefit II

122. Best Time to Buy and Sell Stock II (Easy)

Topic Description: You can be multiple transactions can not be cross between multiple transactions can be carried out multiple transactions.

For [a, b, c, d], if there is a <= b <= c <= d, then the maximum benefit of d - a. And d - a = (d - c) + (c - b) + (b - a), so that when access to a prices [i] and prices [i] - prices [i-1]> 0, then put prices [i] - prices [i-1] is added to the earnings.

public int maxProfit(int[] prices) {
    int profit = 0; for (int i = 1; i < prices.length; i++) { if (prices[i] > prices[i - 1]) { profit += (prices[i] - prices[i - 1]); } } return profit; }

7. planting flowers

605. Can Place Flowers (Easy)

Input: flowerbed = [1,0,0,0,1], n = 1
Output: True

Topic Description: flowerbed array 1 said it had planted the flowers. Flowers interval required between at least one unit, whether solving n planted flowers.

public boolean canPlaceFlowers(int[] flowerbed, int n) {
    int len = flowerbed.length; int cnt = 0; for (int i = 0; i < len && cnt < n; i++) { if (flowerbed[i] == 1) { continue; } int pre = i == 0 ? 0 : flowerbed[i - 1]; int next = i == len - 1 ? 0 : flowerbed[i + 1]; if (pre == 0 && next == 0) { cnt++; flowerbed[i] = 1; } } return cnt >= n; }

8. determines whether sequences

392. Is Subsequence (Medium)

s = "abc", t = "ahbgdc"
Return true.
public boolean isSubsequence(String s, String t) {
    int index = -1; for (char c : s.toCharArray()) { index = t.indexOf(c, index + 1); if (index == -1) { return false; } } return true; }

9. modified to become a non-decreasing number array

665. Non-decreasing Array (Easy)

Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.

Description Title: determining whether only one array can be modified to become a non-decreasing number of arrays.

In nums [i] <nums [i - 1] appears, should be modified to consider which of the array, such that this modification allows the array before the array i becomes non-decreasing, and does not affect the subsequent operation . Priority to make nums [i - 1] = nums [i], because if you modify nums [i] = nums [i - 1] , then nums [i] This number becomes large, there may be more than nums [i + 1] large, thus affecting the subsequent operation. There is a rather special case nums [i] <nums [i - 2], modify nums [i - 1] = nums [i] array can not be nondecreasing array can be modified nums [i] = nums [ i - 1].

public boolean checkPossibility(int[] nums) {
    int cnt = 0; for (int i = 1; i < nums.length && cnt < 2; i++) { if (nums[i] >= nums[i - 1]) { continue; } cnt++; if (i - 2 >= 0 && nums[i - 2] > nums[i]) { nums[i] = nums[i - 1]; } else { nums[i - 1] = nums[i]; } } return cnt <= 1; }

10. The subarray and the largest

53. Maximum Subarray (Easy)

For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
public int maxSubArray(int[] nums) {
    if (nums == null || nums.length == 0) { return 0; } int preSum = nums[0]; int maxSum = preSum; for (int i = 1; i < nums.length; i++) { preSum = preSum > 0 ? preSum + nums[i] : nums[i]; maxSum = Math.max(maxSum, preSum); } return maxSum; }

11. delimited string so that the characters appear together isotype

763. Partition Labels (Medium)

Input: S = "ababcbacadefegdehijhklij"
Output: [9,7,8]
Explanation:
The partition is "ababcbaca", "defegde", "hijhklij".
This is a partition so that each letter appears in at most one part.
A partition like "ababcbacadefegde", "hijhklij" is incorrect, because it splits S into less parts.
public List<Integer> partitionLabels(String S) {
    int[] lastIndexsOfChar = new int[26]; for (int i = 0; i < S.length(); i++) { lastIndexsOfChar[char2Index(S.charAt(i))] = i; } List<Integer> partitions = new ArrayList<>(); int firstIndex = 0; while (firstIndex < S.length()) { int lastIndex = firstIndex; for (int i = firstIndex; i < S.length() && i <= lastIndex; i++) { int index = lastIndexsOfChar[char2Index(S.charAt(i))]; if (index > lastIndex) { lastIndex = index; } } partitions.add(lastIndex - firstIndex + 1); firstIndex = lastIndex + 1; } return partitions; } private int char2Index(char c) { return c - 'a'; }

Guess you like

Origin www.cnblogs.com/daimasanjiaomao/p/11009075.html