[力扣] 算法 525 (C++)

525. 连续数组

class Solution {
	static inline int f(int x)
	{
		return 2 * x - 1;
	}
public:
	int findMaxLength(vector<int>&amp; nums) {
		unordered_map<int, size_t> map;
		nums[0] = f(nums[0]);
		map.emplace(nums[0], 0);
		size_t ret = 0;
		for (size_t i = 1, size = nums.size(), tmp; i < size; ++i)
		{
			nums[i] = nums[i - 1] + f(nums[i]);
			if (nums[i] == 0 &amp;&amp; (tmp = i + 1) > ret)
			{
				ret = tmp;
			}
			else
			{
				auto found = map.find(nums[i]);
				if (found == map.end())
				{
					map.emplace(nums[i], i);
				}
				else if ((tmp = i - found->second) > ret)
				{
					ret = tmp;
				}
			}
		}
		return ret;
	}
};

[力扣] 算法 523 (C++)

523. 连续的子数组和

class Solution {
public:
	bool checkSubarraySum(vector<int>&amp; nums, int k) {
		if (nums.size() < 2)
		{
			return false;
		}
		unordered_map<int, size_t> map;
		map[nums[0] % k] = 0;
		for (size_t i = 1; i < nums.size(); ++i)
		{
			nums[i] += nums[i - 1];
			nums[i] %= k;
			if (nums[i] == 0)
			{
				return true;
			}
			auto found = map.find(nums[i]);
			if (found == map.end())
			{
				map[nums[i]] = i;
			}
			else
			{
				if (i - found->second > 1)
				{
					return true;
				}
			}
		}
		return false;
	}
};

[力扣] 算法 1744 (C++)

1744. 你能在你最喜欢的那天吃到你最喜欢的糖果吗?

class Solution {
public:
	vector<bool> canEat(vector<int>&amp; candiesCount, vector<vector<int>>&amp; queries) {
		vector<long long> tmp(candiesCount.size());
		tmp[0] = candiesCount[0];
		for (size_t i = 1, size = tmp.size(); i < size; ++i)
		{
			tmp[i] += tmp[i - 1] + candiesCount[i];
		}
		vector<bool> ret(queries.size());
		for (size_t i = 0, size = queries.size(); i < size; ++i)
		{
			auto&amp;&amp; query = queries[i];
			int favoriteType = query[0];
			int favoriteDay = query[1];
			long dailyCap = query[2];

			// 往死里吃,必须保证最喜欢的糖果之前的糖果已经全部吃完
			int atLeast = favoriteType > 0 ? tmp[favoriteType - 1] : 0;
			// 一颗一颗吃,必须保证当天至少剩一颗最喜欢的糖
			int limit = tmp[favoriteType];
			// 总共花费的天数
			long day = favoriteDay + 1;

			ret[i] = dailyCap * day > atLeast &amp;&amp; 1 * day <= limit;
		}
		return ret;
	}
};