leetcode-數組-簡單-最大連續1的個數

題目

給定一個二進制數組, 計算其中最大連續1的個數。

來源:

https://leetcode-cn.com/problems/max-consecutive-ones/

示例:

輸入: [1,1,0,1,1,1]
輸出: 3
解釋: 開頭的兩位和最後的三位都是連續1,所以最大連續1的個數是 3.

解答

方法一:

  • 只要遇到1 就繼續往後尋找第一個不是1的數字
  • 記錄個數然後對比最大值
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max_num = 0;
        for (int i = 0; i  < nums.size(); ++i) {
            //只要遇到一個數字等於1, 就開始尋找往後尋找第一個不是1
            if (nums[i] == 1) {
                int count = 0;
                while(true) {
                    if (i == nums.size() || nums[i] == 0) {
                        break;
                    } else if (nums[i] == 1){
                        count++;
                    }
                    i++;
                }
                max_num = max(max_num, count); 
            }
            
        }
        return max_num;
    }
};

方法二:

其實和方法是一樣的,思考問題的細節上略有差異

  • 用兩個變量記錄,一個記錄遇到1開始之後的
  • 一個記錄最大數量
  • 非1就變0
class Solution {
public:
    int findMaxConsecutiveOnes(vector<int>& nums) {
        int max_count = 0;
        int count = 0;
        for (int i = 0; i  < nums.size(); ++i) {
            if (nums[i] == 1) {
                ++count;
            } else {
                max_count = std::max(max_count, count);
                count = 0;
            }
        }
        return std::max(max_count, count);
    }
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章