2023年7月17日 星期一

7/17 每日一題(l返回數組中最多次的連續1)

 Given a binary array nums, return the maximum number of consecutive 1's in the array.

 

Example 1:

Input: nums = [1,1,0,1,1,1]
Output: 3
Explanation: The first two digits or the last three digits are consecutive 1s. The maximum number of consecutive 1s is 3.

Example 2:

Input: nums = [1,0,1,1,0,1]
Output: 2

 

Constraints:

  • 1 <= nums.length <= 105
  • nums[i] is either 0 or 1.


--------------原本搞錯意思  誤會成回傳數組中最大的2進位



nums = [1,1,0,1,1,1]
#轉乘str
nums=[str(i) for i in nums]
new_nums=''.join(nums)
new_list=new_nums.split('0')
res=[int(i,2) for i in new_list]
print(res)
----------------
PS C:\Users\K\OneDrive\桌面\leetcode> & C:/Users/K/AppData/Local/Programs/Python/Python311/python.exe c:/Users/K/OneDrive/ 桌面/leetcode/456.py [3, 7]



-------
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        i=0
        max_one=0
        one=0 #初始化1的次數
        while i < len(nums):
            if nums[i] == 1:
                one +=1  #如果出現1就+1
                max_one=max(max_one,one)
            else:
                one=0 #初始化
            i+=1
        return max_one

--------------參考解答

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        kk = ''.join(map(str, nums))

        ll = kk.split('0')
        max_len = 0
        for i in ll:
            if len(i) > max_len:
                max_len = len(i)
        return(max_len)






























標籤:

0 個意見:

張貼留言

訂閱 張貼留言 [Atom]

<< 首頁