代码随想录算法训练营第三十五天|860.柠檬水找零 406.根据身高重建队列 452. 用最少数量的箭引爆气球

目录

LeeCode 860.柠檬水找零

LeeCode 406.根据身高重建队列

LeeCode 452. 用最少数量的箭引爆气球


LeeCode 860.柠檬水找零

860. 柠檬水找零 - 力扣(LeetCode)

思路:

局部最优:遇到账单20,优先消耗美元10,完成本次找零。全局最优:完成全部账单的找零。

class Solution{
public:
	bool lemonadeChange(vector<int>& bills) {
		int five = 0, ten = 0, twenty = 0;
		for (int bill : bills) {
			if (bill == 5) five++;
			if (bill == 10) {
				if (five <= 0) return false;
				ten++; 
				five--;
			}
			if  (bill == 20) {
				if (five > 0 && ten > 0) {
					five--;ten--;twenty++;
				}
				else if (ten <= 0 && five >= 3){
					five -= 3;
					twenty++;
				}
				else return false;
			}
		}
	return true;
	}
};

时间复杂度:O(n)                  空间复杂度:O(1)


LeeCode 406.根据身高重建队列

406. 根据身高重建队列 - 力扣(LeetCode)

思路:

局部最优:按身高将高的people的k优先插入,插入操作过后的people满足队列属性。全局最优:最后都做完插入操作,整个队列满足题目队列属性。

使用数组进行插入操作:

class Solution {
public:
	static bool cmp(const vector<int>& a, const vector<int>& b) {
		if (a[0] == b[0]) return a[1] < b[1];
    	return a[0] > b[0];
	}
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
    	sort (people.begin(), people.end(), cmp);
    	vector<vector<int>> que;
    	for (int i = 0; i < people.size(); i++) {
    		int position = people[i][1];
    		que.insert(que.begin() + position, people[i]);
		}
		return que;
    }
};

时间复杂度:O(n logn + n²)                  空间复杂度:O(n)

使用链表进行插入操作:

class Solution {
public:
	static bool cmp(const vector<int>& a, const vector<int>& b) {
		if (a[0] == b[0]) return a[1] < b[1];
    	return a[0] > b[0];
	}
    vector<vector<int>> reconstructQueue(vector<vector<int>>& people) {
    	sort (people.begin(), people.end(), cmp);
    	list<vector<int>> que;
    	for (int i = 0; i < people.size(); i++) {
    		int position = people[i][1];
    		std::list<vector<int>>::iterator it = que.begin();
    		while (position --) {
    			it++;
			}
			que.insert(it, people[i]);
		}
	    return vector<vector<int>>(que.begin(), que.end());
    }
};

时间复杂度:O(n logn + n²)                  空间复杂度:O(n)


LeeCode 452. 用最少数量的箭引爆气球

452. 用最少数量的箭引爆气球 - 力扣(LeetCode)

思路:

局部最优:当气球出现重叠,一起射,所用弓箭最少。全局最优:把所有气球射爆所用弓箭最少。

class Solution {
private:
	static bool cmp(const vector<int>& a, const vector<int>& b) {
		return a[0] < b[0];
	}
public:
    int findMinArrowShots(vector<vector<int>>& points) {
    	if (points.size() == 0) return 0;
    	sort(points.begin(), points.end(), cmp);
    	int result = 1;
    	for (int i = 1; i < points.size(); i++) {
    		if (points[i][0] > points[i - 1][1])  result++;
    		else points[i][1] = min(points[i - 1][1], points[i][1]);
		}
	    return result;
    }
};

时间复杂度:O(n logn)                  空间复杂度:O(1)

猜你喜欢

转载自blog.csdn.net/weixin_74976519/article/details/130826537