use the idea just like QuickSort solution(with some explanation)


  • 0
    L

    1、 this solution use the idea just like quicksort
    2、search the array from both sides,if element is 1,then the consecutive nums++(here is leftNums or rightNums)
    3、if left == right && nums[left]=nums[right], the consecutive nums of one is leftNums+1

    public class Solution {
        public int findMaxConsecutiveOnes(int[] nums) {
            //考虑从两侧同时遍历数组
            int leftNum = 0;
            int rightNum = 0;
            int maxConsecutive = 0;
            int left = 0;
            int right = nums.length-1;
            while(left < right){
                leftNum=0;
                rightNum=0;
                while(left<right && nums[left] == 0){
                    left++;
                }
                while(left<right && nums[right] == 0){
                    right--;
                }
                while(left<right && nums[left] == 1){
                    left ++;
                    leftNum++;
                }
                while(left<right && nums[right] == 1){
                    right--;
                    rightNum++;
                }
                maxConsecutive = maxConsecutive>(leftNum>rightNum?leftNum:rightNum)?maxConsecutive:(leftNum>rightNum?leftNum:rightNum);
            }
            if(left == right &&nums[left]==1){
                    leftNum = leftNum + 1;
            }
            maxConsecutive = maxConsecutive>leftNum?maxConsecutive:leftNum;
            return maxConsecutive;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.