LeetCode Array Easy 485. Max Consecutive Ones

 Descriptiongit

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

Example 1:this

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:spa

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

 問題描述: 給定一個二進制數組,計算1連續出現的最屢次數code

個人思路:定義兩個變量,一個counter 記錄出現次數,一個temp 記錄當前出現次數, 若是遇0則temp歸零從新計數。同時考慮邊界狀況blog

public int FindMaxConsecutiveOnes(int[] nums) {
        if(nums.Length == 0)
            return 0;
        int counter = 0;
        int temp = 0;
        for(int i = 0; i < nums.Length; i++){
            if(nums[i] == 1)
            {
                temp++;
            }else
            {
                if(temp > counter)
                {
                    counter = temp;
                }
                temp = 0; 
            }
        }
        if(temp > counter)
        {
            counter = temp;
        }

        return counter;
    }

 

 

相關文章
相關標籤/搜索