一、分发饼干
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
std::sort(g.begin(),g.end());
std::sort(s.begin(),s.end());
int cookie=0,child=0;
while(cookie<s.size()&&child<g.size())
{
if(s[cookie]>=g[child])
{
child++;
}
cookie++;
}
return child;
}
};
二、摇摆序列
class Solution {
public:
int wiggleMaxLength(vector<int>& nums) {
int i,max=1,j=0;
if(nums.size()<2)
return nums.size();
for(i=0;i<nums.size()-1;i++)
{
switch(j)
{
case 0:
{
if(nums[i]<nums[i+1])
{
j=1;
max++;
}
else if(nums[i]>nums[i+1])
{
j=2;
max++;
}
break;
}
case 1:
{
if(nums[i]>nums[i+1])
{
j=2;
max++;
}
break;
}
case 2:
{
if(nums[i]<nums[i+1])
{
j=1;
max++;
}
break;
}
}
}
return max;
}
};
跳跃游戏
class Solution {
public:
bool canJump(vector<int>& nums) {
int i,jump=0,max,j=0;
std::vector<int> index;
for(i=0;i<nums.size();i++)
{
index.push_back(i+nums[i]);
}
max=index[0];
while(j<nums.size()&&j<=max)
{
if(max<index[j])
max=index[j];
j++;
}
if(j==nums.size())
return true;
else
return false;
}
};
跳跃游戏Ⅱ
class Solution {
public:
int jump(vector<int>& nums) {
int i,jump=1,cur=nums[0],pre=nums[0];
if(nums.size()<2)
return 0;
for(i=1;i<nums.size();i++)
{
if(i>cur)
{
jump++;
cur=pre;
}
if(nums[i]+i>pre)
pre=nums[i]+i;
}
return jump;
}
};
射气球相交有两种形式,分别判断shoot_end和point.first和point.end的关系,然后缩短区间
bool cmp(const std::pair<int, int> &a, const std::pair<int ,int> &b) {
return a.first < b.first;
}
class Solution {
public:
int findMinArrowShots(std::vector<std::pair<int, int> >& points) {
if (points.size() == 0){
return 0;
}
std::sort(points.begin(), points.end(), cmp);
int shoot_num = 1;
int shoot_begin = points[0].first;
int shoot_end = points[0].second;
for (int i = 1; i < points.size(); i++){
if (points[i].first <= shoot_end){
shoot_begin = points[i].first;
if (shoot_end > points[i].second){
shoot_end = points[i].second;
}
}
else{
shoot_num++;
shoot_begin = points[i].first;
shoot_end = points[i].second;
}
}
return shoot_num;
}
};