iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
自我挑戰組

FRIENDS系列 第 7

Day 7: LeetCode 485. Max Consecutive Ones

Tag:隨意刷-每月挑戰(2021.09.21)

Source:

485. Max Consecutive Ones

1.題意:

如題目: 回傳最長連續的1
In: binary array nums
Out: the maximum number of consecutive 1's in the array

2.思路:

  • 遍歷nums
    • 遇1則tmpLen++且更新最大連續1長度(maxLen)
    • 遇0則tmpLen歸零

3.程式碼:

Python3

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        
        maxLen = 0
        tmpLen = 0
        for i in nums:
            if i == 1:
                tmpLen+=1
                maxLen=max(maxLen,tmpLen)
            else:
                tmpLen=0
                
        return maxLen 

Java

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int tmpLen = 0;
        int maxLen = 0;
        for(int i=0;i<nums.length;i++)
        {
            if(nums[i]==1)
            {
                tmpLen++;
                maxLen=Math.max(tmpLen,maxLen);
            }
            else
            {
                tmpLen=0;
            }
        }
        return maxLen;
    }
}

Result:

Level:Easy


上一篇
Day 6: LeetCode 54. Spiral Matrix
下一篇
Day 8: Recap Day [1-7] & Enhance
系列文
FRIENDS30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

0
soft_soft
iT邦新手 5 級 ‧ 2021-09-22 19:21:04

隨意抓~隨意打~

阿瑜 iT邦研究生 4 級 ‧ 2021-09-23 00:13:32 檢舉

應該來個目的刷才對,但我可能要switch 到另一個主題內容了

我要留言

立即登入留言