【leetcode】最大连续1的个数III

 

滑动窗口解法:

public class Main {
	 public int longestOnes(int[] A, int K) {
		//	count 是记录最长的长度
		 int count = 0;
		 //如果K>=A.length 说明A所有0的位置都可以变成1
			if (K >= A.length)
				return A.length;
			//另外
			else 
			{//zoreSum 记录 i 遍历1到另外一个1之后的0的数量//flag记录第一个滑动窗口的左边位置 ,右边位置为i
				int zoreSum = 0;
				int flag = 0;
				for (int i = 0; i < A.length; i++) {
					if (A[K] != 1) 
					{
						zoreSum++;
					}
					//如果超过K个0 如K=3 zoreSum=4   "111"100001->00010"111"1 
					//zoreSum =3 的话 还可以连在一起 "111"10001 ->01"111"1
					while (zoreSum > K) {
						if (A[flag] == 0) 
						{
							zoreSum--;
						}
						flag++;
					}
					//zoreSum 减到K 则回复正常
					count = Math.max(count, i - flag + 1);
				}
			}
			return count;
		}

动态规划解法

用两个for 

public int longestOnes(int[] A, int K) {
    int max = 0;
    int[] cur = new int[K+1];        
    for(int i = 0; i < A.length; ++i) {
        for(int j = K; j >= 0; --j) {
            if(A[i] == 1) {
                cur[j]++;
            }
            else {
                if(j == 0) {
                    cur[j] = 0;
                }
                else {
                    cur[j] = cur[j-1] + 1;    
                }
            }            
            max = Math.max(max, cur[j]);
        }
    }
    return max;
}

猜你喜欢

转载自blog.csdn.net/kevin_nan/article/details/88146342