记录了初步解题思路 以及本地实现代码;并不一定为最优 也希望大家能一起探讨 一起进步
目录
- 6/10 881. 救生艇
- 6/11 419. 甲板上的战舰
- 6/12 2806. 取整购买后的账户余额
- 6/13 2813. 子序列最大优雅度
- 6/14 2786. 访问数组中的位置使分数最大
- 6/15 2779. 数组的最大美丽值
- 6/16
6/10 881. 救生艇
将体重从小到大排序
双指针尽量让体重大的和体重小的一起
如果当前最重和最轻的无法坐一艘船 那么最重的必定要一个人一艘
def numRescueBoats(people, limit):""":type people: List[int]:type limit: int:rtype: int"""people.sort()ans = 0l,r=0,len(people)-1while l<=r:ans +=1if people[l]+people[r]<=limit:l+=1r-=1else:r-=1return ans
6/11 419. 甲板上的战舰
遍历每一个位置 遇到战舰
对着搜战舰进行搜索 记录该战舰的所有位置在mem中
战舰数量+1
def countBattleships(board):""":type board: List[List[str]]:rtype: int"""m,n=len(board),len(board[0])mem = set()def func(i,j):if (i,j) in mem:return mem.add((i,j))for ai,aj in [(1,0),(-1,0),(0,1),(0,-1)]:ni,nj=i+ai,j+ajif 0<=ni<m and 0<=nj<n and board[ni][nj]=='X':func(ni,nj)ans = 0for i in range(m):for j in range(n):if board[i][j]=='X' and (i,j) not in mem:func(i,j)ans +=1return ans
6/12 2806. 取整购买后的账户余额
四舍五入
def accountBalanceAfterPurchase(purchaseAmount):""":type purchaseAmount: int:rtype: int"""base = purchaseAmount//10if purchaseAmount%10>4:base +=1return 100-10*base
6/13 2813. 子序列最大优雅度
将利润从大到小排序
假设已经选取了最大前k个利润的项目
对于当前项目x
如果x的类别已经出现在k个项目中 那么不用考虑
如果没有出现在k个项目中 挑选移除的一个项目
如果移除的项目只出现过一次 那么多一个类别少一个类别 不影响结果 所以不考虑
如果出现过多次 那么distinct会增加 total_profit会减少 如果能够使得总和变大就选
def findMaximumElegance(items, k):""":type items: List[List[int]]:type k: int:rtype: int"""items.sort(key=lambda x:-x[0])ans = 0mem = set()total = 0d = []for i,(p,c) in enumerate(items):if i<k:total += pif c not in mem:mem.add(c)else:d.append(p)elif d and c not in mem:mem.add(c)total += p-d.pop()ans = max(ans,total+len(mem)**2)return ans
6/14 2786. 访问数组中的位置使分数最大
从头遍历 记录奇、偶两种情况左侧的最大值
def maxScore(nums, x):""":type nums: List[int]:type x: int:rtype: int"""ans = nums[0]odd,even=float("-inf"),float("-inf")if nums[0]%2==0:even=nums[0]else:odd=nums[0]for i in range(1,len(nums)):v = nums[i]if v%2==0:cur = max(even+v,odd+v-x)ans = max(ans,cur)even = max(even,cur)else:cur = max(even+v-x,odd+v)ans = max(ans,cur)odd = max(odd,cur)return ans
6/15 2779. 数组的最大美丽值
从小到大排序
选定最大值nums[j] 可以得到最小值nums[j]-2*k<=nums[i]
双指针 确定了j 可以不断右移i直到不满足条件
def maximumBeauty(nums, k):""":type nums: List[int]:type k: int:rtype: int"""nums.sort()ans = 0n = len(nums)i = 0for j in range(n):while nums[j]-2*k>nums[i]:i+=1ans = max(ans,j-i+1)return ans
6/16