Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最长子串拓展的问题 #14

Open
JesseZhao1990 opened this issue Jun 27, 2018 · 0 comments
Open

最长子串拓展的问题 #14

JesseZhao1990 opened this issue Jun 27, 2018 · 0 comments

Comments

@JesseZhao1990
Copy link
Owner

一个只有0和1的数组,如果将此数组中的某一个0换成1,得到连续1的最大值是多少。

比如 [0,1,1,0,1,1],将第二个0换成1能出现五个连续的1. 所以值是5,

解题思路: 双指针滑动窗口+记录滑动块内的零的数量



function find(arr){
    var max = 0;
    var p1 =0;
    var p2 =1;
    var zeroNum = 0;
    var length = arr.length;
    if(length === 1) return 1;

    if(arr[p1]=== 0) zeroNum ++;
    if(arr[p2]===0)  zeroNum ++;

    while(p2<length){
        if(p1===p2){
            p2++;
            if(arr[p2]=== 0) zeroNum ++;
        }   
        if(arr[p2] === 1){
            p2++;
            if(arr[p2]=== 0) zeroNum ++;
            if(p2 == length) max = Math.max(max,p2-p1);
        }else{
            if(zeroNum<2){
                p2++;
                if(arr[p2]=== 0) zeroNum ++;
            }else{
                max = Math.max(max,p2-p1);
                if(arr[p1]===0){
                    zeroNum --;
                }
                p1++;
            }
        }
    }
    return max;
}

var arr1 = [0,1,1,0,0,0,1,1,1,0,1,1,1,0,0,1,1,1,1,0,1,1,1,1,0,0]
var arr2 = [0,1,1,0]
var arr3 = [0,1]
var arr4 = [0]
var arr5 = [1]

console.log(find(arr1))
console.log(find(arr2))
console.log(find(arr3))
console.log(find(arr4))
console.log(find(arr5))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant