文章目录
前言
我的五月刷题日记,今天的题目比较简单,先打个卡,晚上把昨天落下的补上。
第四天:贪心算法
一、练习题目
| 题目链接 | 难度 |
|---|---|
| 1221. 分割平衡字符串 | ★☆☆☆☆ |
| 1827. 最少操作使数组递增 | ★☆☆☆☆ |
| 2144. 打折购买糖果的最小开销 | ★☆☆☆☆ |
| 1400. 构造 K 个回文字符串 | ★★☆☆☆ |
二、思路与代码
1. 分割平衡字符串
遍历字符串,设置计数器,遇到L,变量pos加一,遇到R,变量pos减一,若变量为零,则计数器加一,返回计数器。
class Solution(object):
def balancedStringSplit(self, s):
"""
:type s: str
:rtype: int
"""
pos = 0
count = 0
if len(s) == 0:
return 0
for i in s:
if i == 'L':
pos += 1
if i == 'R':
pos -= 1
if pos == 0:
count += 1
return count
2.最少操作使数组递增

遍历数组,后一个数组比起哪一个小,则加上一个数,使后一个数大于前一个数;若后一个数比前一个数大,则不变。
class Solution(object):
def minOperations(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
count = 0
n = len(nums)
for i in range(n-1):
if nums[i+1] <= nums[i]:
count += nums[i] - nums[i+1] + 1
nums[i+1] = nums[i] + 1
else:
nums[i+1] = nums[i+1]
return count
3.打折购买糖果的最小开销

解题思路
class Solution(object):
def minimumCost(self, cost):
"""
:type cost: List[int]
:rtype: int
"""
cost.sort(reverse = True)
n = len(cost)
discount = 0
for i in range(n):
if i % 3 == 2:
discount += cost[i]
return sum(cost) - discount
4.构造 K 个回文字符串

参考钵钵酱分享的思路,如下:
class Solution(object):
def canConstruct(self, s, k):
"""
:type s: str
:type k: int
:rtype: bool
"""
hash = [0] * 26 #构造哈希表
twoCount = 0
oneCount = 0
s.lower()
for i in s:
hash[ord(i) - ord('a')] += 1
for i in range(26):
twoCount += hash[i] // 2
oneCount += hash[i] % 2
if k >= oneCount and k <= 2 * twoCount + oneCount:
return True
else:
return False
本文记录了五月刷题第四天的贪心算法练习,包括分割平衡字符串、最少操作使数组递增、打折购买糖果的最小开销及构造回文字符串等题目,通过代码实现解题思路。

503

被折叠的 条评论
为什么被折叠?



