当前位置:   article > 正文

[Leetcode] 每日两题 1864 961 -day61_leetcode 1864

leetcode 1864
1864. 构成交替字符串需要的最小交换次数

在这里插入图片描述

根据贪心的思想,我们可以统计偶数位上1的数量和0的数量,那看哪个更多,这样就移动更少的那个,也就是min(len(s)//2 -res0,len(s)//2 -res1),但是面对序列为奇数个字母时,只能用更少的元素放在偶数位,就不能取min

class Solution:
    def minSwaps(self, s: str) -> int:
        num0,res0 =0,0
        num1,res1 =0,0
        for i in range(0,len(s)):
            if s[i] =='0':
                num0 += 1
                if i %2:
                    res0+=1
            else :
                num1 +=1
                if i %2 :
                    res1+=1
        if num0 != len(s)//2 and num1 != len(s)//2:
            return -1
        if  num0 <num1:
            return len(s)//2 -res0
        if  num0 >num1:
            return len(s)//2 -res1
        return min(len(s)//2 -res0,len(s)//2 -res1)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
961. 在长度 2N 的数组中找出重复 N 次的元素

在这里插入图片描述

首先 由于目标元素是N个 在2N 长度的数组里放 N 个元素, 那这些元素的最小距离肯定是小于等于3的,所以可以直接 判断该元素和它前三个元素是否有相等来寻找该元素,最后返回一下边界。

class Solution:
    def repeatedNTimes(self, nums: List[int]) -> int:
        for i in range(len(nums)-3):
            if nums[i] ==nums[i+1] or nums[i] == nums[i+2] or nums[i]==nums[i+3]:
                return nums[i]
        if nums[len(nums)-3] ==nums[len(nums)-2] or nums[len(nums)-3] ==nums[len(nums)-1]:
            return nums[len(nums)-3]
        return nums[len(nums)-2]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/588080
推荐阅读
相关标签
  

闽ICP备14008679号