贪心思想

455. Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.

Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.

Example:
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.

class Solution {
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
        std::sort(g.begin(),g.end());
        std::sort(s.begin(),s.end());
        int gi = 0, si = 0;
        while(gi<g.size() && si<s.size()){
            if(g[gi]<=s[si]) gi++;
            si++;
        }
        return gi;
    }
};

435. Non-overlapping Intervals

Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Note:
You may assume the interval’s end point is always bigger than its start point.
Intervals like [1,2] and [2,3] have borders “touching” but they don’t overlap each other.
Example 1:
Input: [ [1,2], [2,3], [3,4], [1,3] ]

Output: 1

Explanation: [1,3] can be removed and the rest of intervals are non-overlapping.
Example 2:
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.

/**
 * Definition for an interval.
 * struct Interval {
 *     int start;
 *     int end;
 *     Interval() : start(0), end(0) {}
 *     Interval(int s, int e) : start(s), end(e) {}
 * };
 */
bool comp(Interval& i1, Interval& i2){
    return i1.end<i2.end;
}
class Solution {
public:
    int eraseOverlapIntervals(vector<Interval>& intervals) {
        if(intervals.empty()) return 0;
        std::sort(intervals.begin(),intervals.end(),comp);
        int cnt = 1;
        int end = intervals[0].end;
        for(int i=1; i<intervals.size(); ++i){
            if(intervals[i].start < end) continue;
            end = intervals[i].end;
            cnt++;
        }
        return intervals.size() - cnt;
    }
};

452. Minimum Number of Arrows to Burst Balloons

There are a number of spherical balloons spread in two-dimensional space. For each balloon, provided input is the start and end coordinates of the horizontal diameter. Since it’s horizontal, y-coordinates don’t matter and hence the x-coordinates of start and end of the diameter suffice. Start is always smaller than end. There will be at most 104 balloons.

An arrow can be shot up exactly vertically from different points along the x-axis. A balloon with xstart and xend bursts by an arrow shot at x if xstart ≤ x ≤ xend. There is no limit to the number of arrows that can be shot. An arrow once shot keeps travelling up infinitely. The problem is to find the minimum number of arrows that must be shot to burst all balloons.

Example:

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

Output:
2

Explanation:
One way is to shoot one arrow for example at x = 6 (bursting the balloons [2,8] and [1,6]) and another arrow at x = 11 (bursting the other two balloons).

bool comp(const pair<int, int>& p1, const pair<int, int>& p2){
    return p1.second<p2.second;
}
class Solution {
public:
    int findMinArrowShots(vector<pair<int, int>>& points) {
        if (points.empty()) return 0;
        std::sort(points.begin(),points.end(),comp);
        int cnt = 1;
        int end = points[0].second;
        for (int i = 1; i < points.size(); ++i){
            if (points[i].first <= end) continue;
            end = points[i].second;
            cnt++;
        }
        return cnt;
    }
};

406. Queue Reconstruction by Height

Suppose you have a random list of people standing in a queue. Each person is described by a pair of integers (h, k), where h is the height of the person and k is the number of people in front of this person who have a height greater than or equal to h. Write an algorithm to reconstruct the queue.

Note:
The number of people is less than 1,100.

Example

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]]

bool comp(const pair<int,int>& p1, const pair<int,int>& p2){
    if (p1.first == p2.first) return p1.second < p2.second;
    return p1.first > p2.first;
}
class Solution {
public:
    vector<pair<int, int>> reconstructQueue(vector<pair<int, int>>& people) {
        std::sort(people.begin(),people.end(),comp);
        vector<pair<int,int>> ans;
        ans.clear();
        for(auto i : people){
            ans.insert(ans.begin()+i.second, i);
        }
        return ans;
    }
};

763. Partition Labels

A string S of lowercase letters is given. We want to partition this string into as many parts as possible so that each letter appears in at most one part, and return a list of integers representing the size of these parts.

Example 1:
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.

class Solution {
public:
    vector<int> partitionLabels(string S) {
        vector<int> ans;
        int n = S.size(), start = 0, last = 0;
        unordered_map<char, int> m;
        for(int i=0; i<n; ++i) m[S[i]] = i;
        for(int i=0; i<n; ++i){
            last = max(last, m[S[i]]);
            if(i==last){
                ans.push_back(last-start+1);
                start = last + 1;
            }
        }
        return ans;
    }
};

605. Can Place Flowers

Suppose you have a long flowerbed in which some of the plots are planted and some are not. However, flowers cannot be planted in adjacent plots - they would compete for water and both would die.

Given a flowerbed (represented as an array containing 0 and 1, where 0 means empty and 1 means not empty), and a number n, return if n new flowers can be planted in it without violating the no-adjacent-flowers rule.

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

class Solution {
public:
    bool canPlaceFlowers(vector<int>& flowerbed, int n) {
        int len = flowerbed.size();
        int cnt = 0;
        for(int i=0; i<len;++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 n<=cnt;
    }
};

392. Is Subsequence

Given a string s and a string t, check if s is subsequence of t.

You may assume that there is only lower case English letters in both s and t. t is potentially a very long (length ~= 500,000) string, and s is a short string (<=100).

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, “ace” is a subsequence of “abcde” while “aec” is not).

Example 1:
s = “abc”, t = “ahbgdc”

Return true.

class Solution {
public:
    bool isSubsequence(string s, string t) {
        int si=0,ti=0;
        while(si<s.size() && ti<t.size()){
            if(s[si]==t[ti]) si++;
            ti++;
        }
        return si == s.size();
    }
};

665. Non-decreasing Array

Given an array with n integers, your task is to check if it could become non-decreasing by modifying at most 1 element.

We define an array is non-decreasing if array[i] <= array[i + 1] holds for every i (1 <= i < n).

Example 1:
Input: [4,2,3]
Output: True
Explanation: You could modify the first 4 to 1 to get a non-decreasing array.
Example 2:
Input: [4,2,1]
Output: False
Explanation: You can’t get a non-decreasing array by modify at most one element.

class Solution {
public:
    bool checkPossibility(vector<int>& nums) {
        int cnt = 0;
        for (int i = 0; i<nums.size()-1; ++i){
            if(nums[i] <= nums[i+1]) continue;
            cnt++;
            if(i-1>=0 && nums[i-1]>nums[i+1]) nums[i+1]=nums[i];
            else nums[i]=nums[i+1];
        }
        return cnt<2;
    }
};

122. Best Time to Buy and Sell Stock II

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int ans = 0;
        int n = prices.size();
        for(int i = 0; i < n-1; ++i){
            if(prices[i]<prices[i+1]) ans += prices[i+1]-prices[i];
        }
        return ans;
    }
};

猜你喜欢

转载自blog.csdn.net/xzy_thu/article/details/81076110
今日推荐