I couldn’t choose this career I couldn’t choose this life, y’all had to choose it for me, y’all chose me, and I take that very seriously. Even if y’all don’t understand what I’m doing sometimes or the music I made sometimes, I just take that responsibility very seriously, you know, to innovate and not imitate, to demonstrate that all limits is fake. And I never felt as much love in one building as I felt tonight. All things are possible through love..
leedcode768 最多能完成排序的块II
arr是一个可能包含重复元素的整数数组,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。
我们最多能将数组分成多少块?
示例 1:
输入: arr = [5,4,3,2,1]
输出: 1
解释:
将数组分成2块或者更多块,都无法得到所需的结果。
例如,分成 [5, 4], [3, 2, 1] 的结果是 [4, 5, 1, 2, 3],这不是有序的数组。
示例 2:
输入: arr = [2,1,3,4,4]
输出: 4
解释:
我们可以把它分成两块,例如 [2, 1], [3, 4, 4]。
然而,分成 [2, 1], [3], [4], [4] 可以得到最多的块数。
来源:力扣(LeetCode)
链接:网页链接
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
cnt = Counter()#计数函数 创建哈希表cnt
res = 0
for x, y in zip(arr, sorted(arr)):
cnt[x] += 1#//#/对原表中的元素计数
if cnt[x] == 0:
del cnt[x]#//#/当个数为0时删除
cnt[y] -= 1#//#/排序后的对应元素-1
if cnt[y] == 0:
del cnt[y]#//#/为0时-1
if len(cnt) == 0:
res += 1#//#/当哈希表为空时说明两个前面的元素出现的频数相同 这样的话排序后无差别
return res
# 作者:LeetCode-Solution
# 链接:网页链接
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
arr是一个可能包含重复元素的整数数组,我们将这个数组分割成几个“块”,并将这些块分别进行排序。之后再连接起来,使得连接的结果和按升序排序后的原数组相同。
我们最多能将数组分成多少块?
示例 1:
输入: arr = [5,4,3,2,1]
输出: 1
解释:
将数组分成2块或者更多块,都无法得到所需的结果。
例如,分成 [5, 4], [3, 2, 1] 的结果是 [4, 5, 1, 2, 3],这不是有序的数组。
示例 2:
输入: arr = [2,1,3,4,4]
输出: 4
解释:
我们可以把它分成两块,例如 [2, 1], [3, 4, 4]。
然而,分成 [2, 1], [3], [4], [4] 可以得到最多的块数。
来源:力扣(LeetCode)
链接:网页链接
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
代码:
class Solution:
def maxChunksToSorted(self, arr: List[int]) -> int:
cnt = Counter()#计数函数 创建哈希表cnt
res = 0
for x, y in zip(arr, sorted(arr)):
cnt[x] += 1#//#/对原表中的元素计数
if cnt[x] == 0:
del cnt[x]#//#/当个数为0时删除
cnt[y] -= 1#//#/排序后的对应元素-1
if cnt[y] == 0:
del cnt[y]#//#/为0时-1
if len(cnt) == 0:
res += 1#//#/当哈希表为空时说明两个前面的元素出现的频数相同 这样的话排序后无差别
return res
# 作者:LeetCode-Solution
# 链接:网页链接
# 来源:力扣(LeetCode)
# 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
1184—₀₁₀₈ˡʸⁿ
If the time is the best time, it is the time to meet you.[给你小心心]
That forever summer.
In 2018。
#刘宇宁的温暖"神器"# #刘宇宁小林暖宝宝代言人#
@摩登兄弟刘宇宁
『一切亘古不变的都是爱你的痕迹,比如月亮阴晴圆缺,比如太阳从东方升起,比如牛顿第一定律,比如我爱你。』
[掌宝爱心]
https://t.cn/A6MzXKiy
#爱豆v能量##摩登兄弟[超话]#
If the time is the best time, it is the time to meet you.[给你小心心]
That forever summer.
In 2018。
#刘宇宁的温暖"神器"# #刘宇宁小林暖宝宝代言人#
@摩登兄弟刘宇宁
『一切亘古不变的都是爱你的痕迹,比如月亮阴晴圆缺,比如太阳从东方升起,比如牛顿第一定律,比如我爱你。』
[掌宝爱心]
https://t.cn/A6MzXKiy
#爱豆v能量##摩登兄弟[超话]#
✋热门推荐