LeetCode 485. Max Consecutive Ones

题目描述 LeetCode 485

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.

题目分析

  • 本题是找出数组中连续的 1 的最大个数,如实例中给出 [1, 1, 0, 1, 1, 1] 中连续的 1 分别为 2 个和 3 个,所以说输出为 3
  • 比较坑的地方是:
    • 第一,如果数组中没有 1 ,呢,则输出为 0.(也就是数组中连续 1 个数为 0)
    • 第二,如果数组中,1 的个数很少呢,比如 [0, 0, 1, 0, 0] ,这种情况下,输出 1 的个数为 1.

解题思路

  • 建立一个辅助数组 temp,大小与原数组一样,每次循环初始化为 -1,然后每次,如果 nums[i] == 1,则如果 nums[i] == nums[i-1],temp[i] = temp[i-1]+1;如果 nums[i] != nums[i-1],temp[i] = 1。如果 nums[i] == 0,那么 temp[i] = -1 不变。
  • 实例:
    • 如果输入数组为 [0, 0, 1, 0, 0],则辅助数组最终达成的效果为 temp = [-1, -1, 1, -1, -1],最终输出 1
    • 如果输入数组为 [1, 1, 0, 1, 1, 1],则辅助数组最终达成的效果为 temp = [1, 2, -1, 1, 2, 3],最终输出 3

Code

# include

int findMaxConsecutiveOnes(int* nums, int numsSize) {
    int i;
    int max = 0;
    int flag = 0; 
    int temp[10000];

    for (i = 0; i < numsSize; i ++){
        temp[i] = -1;
        if (i == 0){
            if(nums[i] == 1){
                temp[i] = 1;
            }
        }
        else{
            if(nums[i] == 1){
                if (nums[i] == nums[i-1]){
                    temp[i] = temp[i-1] + 1;
                }
                else{
                    temp[i] = 1;
                }
            }
        }

        if(nums[i] == 1){
            flag = 1;
        }

        if (max < temp[i]){
            max = temp[i];
        }
        //printf("%d ", temp[i]);
    }

    //printf("flag = %d\n",flag );
    if (flag == 0){
        return 0;
    }
    else{
        return max;
    }
}

int main(){ 
    // int a[10] = {1, 1, 0, 1, 1, 1};
    int a[10] = {0, 0, 1, 0, 0};
    printf("\n\n%d\n\n",findMaxConsecutiveOnes(a, 5));
}
LeetCode 485. Max Consecutive Ones_第1张图片

你可能感兴趣的:(LeetCode 485. Max Consecutive Ones)