Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How does leetcode calculate the number of maximum consecutive ones

2025-04-10 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces how leetcode calculates the number of maximum consecutive 1s, which is very detailed and has a certain reference value. Friends who are interested must read it!

I. the content of the topic

Given a binary array, calculate the number of maximum consecutive ones in it.

Example:

Input: [1pyrum 1pcr0pl 1p1p1pl]

Output: 3

Explanation: the first two digits and the last three digits are consecutive ones, so the maximum number of consecutive ones is 3.

Tip:

The array entered contains only 0 and 1.

The length of the input array is a positive integer and does not exceed 10000.

Second, the way to solve the problem

1. Record the length directly and then compare the size each time.

two。 Slide the window, increase the window length each time until it is 0, record the length and compare the current maximum length, and then start recording the length again from where it is 1, so you can compare it over and over again.

Code class Solution: def findMaxConsecutiveOnes1 (self, nums: list)-> int: count = 0 ans = 0 for num in nums: if num = = 1: count + = 1 ans = max (ans, count) else: count = 0 return ans def findMaxConsecutiveOnes2 (self, nums: list)-> int: left, right = 0 0 ans = 0 while right < len (nums): if nums [right] = = 1: right + = 1 else: ans = max (ans, right-left) right + = 1 left = right ans = max (ans Right-left) return ansif _ _ name__ ='_ _ main__': s = Solution () nums = [1, 1, 0, 1, 1, 1] ans1 = s.findMaxConsecutiveOnes1 (nums) print (ans1) ans2 = s.findMaxConsecutiveOnes2 (nums) print (ans2) all the contents of the article "how leetcode calculates the maximum number of consecutive ones" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report