[Leetcode]485. Max Consecutive Ones


求出連續相連幾個數字1

Given a binary array, find the maximum number of consecutive 1s in this array.

Example 1:

Input: [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.

Note:

  • The input array will only contain 0 and 1.
  • The length of input array is a positive integer and will not exceed 10,000

Think:
  1. 宣告一個記數、暫存
  2. 計算如果遇到1就加一,反之是0 就歸零
  3. 當num[i]==0 時,判斷 記數是否大於暫存 ,是 則將 記數值存入暫存

JAVA

class Solution {
    public int findMaxConsecutiveOnes(int[] nums) {
        int count = 0;
        int tem = 0;
        for(int i = 0; i<nums.length;i++){
            if(nums[i]==1){
                count++;
            }
            else{
                if(count>=tem){
                    tem=count;
                }
                
                count=0;
            }
        }
        
        if(count>=tem){
                    tem=count;
                   
                }
         return tem;
               
    }
}

留言

這個網誌中的熱門文章

[HTML]標籤-下

論P, NP, NP-Complete, NP-Hard問題

[Python]基礎課程

[系統]解除電腦限制頻寬

[HTML]標籤-上

[AlaSQL] 多data查詢+累計

How to Check the MySQL Version

[SQL Sever] 日期時間

推薦使用的9款編程字體

類別型態 vs 基本型態