leetcode_list 485.最大连续1的个数

本文介绍了一种算法,用于解决给定二进制数组中找到最大连续1的个数的问题。通过在数组首尾添加0,并记录0的位置,最后计算相邻0之间的距离来找出最长的连续1序列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:给定一个二进制数组,计算其中最大连续1的个数。

示例1:

输入:[1,1,0,1,1,1]

输出:3

解释:开头的两位和最后的三位都是连续1,所以最大连续1的个数是3

注意:

  • 输入的数组只包含0和1
  • 输入的数组的长度是正整数,且不超过10000.

思路:因为题目只需求最大连续1的个数,考虑到开头和末尾都有可能为1,所以我们在列表的首尾各自添加1个0,接着遍历一遍数组,记录出现0的索引的数组,最后再遍历一遍新创建的数组,取相邻索引所对应的元素的差再减去1的最大值就是目标值。

class Solution:
    def findMaxConsecutiveOnes(self,nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result_list,max_nums = [],0
        new_nums = [0] + nums + [0]
        for i in range(len(new_nums)):
            if new_nums[i] == 0:
                result_list.append(i)
        for j in range(1,len(result_list)):
            max_num = max(max_num,result_list[j] - result_list[j-1] - 1)
        return max_num

 

### LeetCode Problems Involving Counting the Number of 1s in Binary Representation #### Problem Description from LeetCode 191. Number of 1 Bits A task involves writing a function that receives an unsigned integer and returns the quantity of '1' bits within its binary form. The focus lies on identifying and tallying these specific bit values present in any given input number[^1]. ```python class Solution: def hammingWeight(self, n: int) -> int: count = 0 while n: count += n & 1 n >>= 1 return count ``` This Python code snippet demonstrates how to implement the solution using bitwise operations. #### Problem Description from LeetCode 338. Counting Bits Another related challenge requires generating an output list where each element represents the amount of set bits ('1') found in the binary notation for integers ranging from `0` up to a specified value `n`. This problem emphasizes creating an efficient algorithm capable of handling ranges efficiently[^4]. ```python def countBits(num): result = [0] * (num + 1) for i in range(1, num + 1): result[i] = result[i >> 1] + (i & 1) return result ``` Here, dynamic programming principles are applied alongside bitwise shifts (`>>`) and AND (`&`) operators to optimize performance during computation. #### Explanation Using Brian Kernighan Algorithm For optimizing further especially with large inputs, applying algorithms like **Brian Kernighan** offers significant advantages due to reduced iterations needed per operation compared against straightforward methods iterating through all possible positions or dividing repeatedly until reaching zero. The core idea behind this method relies upon subtracting powers-of-two corresponding only to those places holding actual ‘ones’ thereby skipping over zeroes entirely thus reducing unnecessary checks: ```python def hammingWeight(n): count = 0 while n != 0: n &= (n - 1) count += 1 return count ``` --related questions-- 1. How does the Hamming weight calculation differ between signed versus unsigned integers? 2. Can you explain why shifting right works effectively when determining counts of one-bits? 3. What optimizations exist beyond basic iteration techniques for calculating bit counts? 4. Is there any difference in implementation logic required across various programming languages supporting similar syntaxes? 5. Why might someone choose the Brian Kernighan approach over other strategies?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值