Likou 455. Distributing biscuits【C++】

topic description

insert image description here

problem solving ideas

Just be greedy, get the global optimal solution through the local optimal solution (we can try to write the code as long as we can’t give obvious counterexamples), the idea of ​​this question is: give him the biggest biscuit first to satisfy his appetite . child

class Solution {
    
    
public:
    int findContentChildren(vector<int>& g, vector<int>& s) {
    
    
        //孩子胃口
		sort(g.begin(),g.end());
		//饼干体积
		sort(s.begin(),s.end());
		int index,result=0;
		index = s.size()-1;
		// 这里必须for遍历孩子,while遍历饼干
		for(int i = g.size()-1;i >= 0;i--){
    
    
			while(index>=0&&s[index]>=g[i]){
    
    
				result++;
				index--;
				break;//注意这里一定要跳出while循环,不然答案不对例如 g[]={1,2,3} s[]={1,1},答案应该是1但是如果不加break答案是2
			}
		}

		return result;
    }
};

another way of thinking

This question can also be thought of from another angle, the smallest biscuit is fed to a child with a small appetite that he can satisfy.

Guess you like

Origin blog.csdn.net/qq_63524016/article/details/129330535