9月3号Leetcode

92 阅读1分钟

早上做了四道题,都是很经典的题,自己还是太菜,加油吧

1.leetcode485题 最大连续1的个数

dp可以解决 ,但是好像效率不太高? 

    public int findMaxConsecutiveOnes(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n + 1];
        dp[0] = 0;
        int res = 0;
        for(int i = 1;i <= n;i++){
            if(nums[i - 1] == 1){
                dp[i] = dp[i - 1] + 1;
                res = Math.max(res,dp[i]);
            }
        }
        return res;
    }

2.leetcode1004题 最大连续1的个数III

界定k个可以变化成1的数,问最大连续1的个数

用暴力超时了

自己用hashmap来存,一直出问题。。。 用第三题那样的思路,边界总是有问题~ 沮丧

简单的滑动窗口

还没有真正领略到滑动窗口的本质吧

class Solution {
    public int longestOnes(int[] A, int K) {
        int n = A.length;
        int res = 0;
        int left = 0;
        int preSum = 0;
        for (int right = 0;right < n;right++){
            preSum += A[right] == 0 ? 1 : 0;
            if (preSum > K){
                while (left < right && A[left] == 1){
                    left++;
                }
                preSum--;
                left++;
            }
            res = Math.max(res,right - left + 1);

        }
        return res;
    }
}

3.leetcode718题 

dp! 二维dp

4.leetcode424题 替换后的最长重复字符

这个题也是滑动窗口,单纯用暴力来写的时候,没有考虑到可以向前扩展,比如ABBBA的情况! 应该用一个变量保存当前窗口里的最大值,然后判断长度-这个最大值是否大于k,也就是是否可以通过k个变化达到相等

class Solution {
    public int characterReplacement(String s, int k) {
                int n = s.length();
        int res = 0;
        int curMaxLen = -1;
        Map<Character,Integer> map = new HashMap<>();
        for (int left = 0, right = 0;right < n;right++){
            char temp = s.charAt(right);
            map.put(temp,map.getOrDefault(temp,0) + 1);
            curMaxLen = Math.max(curMaxLen,map.get(temp));
            while (right - left + 1 - curMaxLen > k){
                map.put(s.charAt(left),map.getOrDefault(s.charAt(left),0) - 1);
                left++;
            }
            res = Math.max(res,right - left + 1);

        }
        return res;
    }
}