leetcode-2024. 考试的最大困扰度

leetcode-2024. 考试的最大困扰度

    • 题源
    • 知识点
    • 思路
    • 代码
      • Java
      • JavaScript
      • python
      • C

题源

  • 2024. 考试的最大困扰度

知识点

  • 滑动窗口

思路

  • 滑动窗口,是用双指针而形成的,指针都是从最左边开始的,再次右指针一直右移动,而左指针对条件进行判断('T'或者'F'的数目的最小值与k比较),因为是判断,则左指针和右指针的差一定是越来越大,而不会缩小

代码

Java

  • 在写java的时候,习惯新把字符串当作数组来用。在java里面数组是数组,字符串是字符串。
  • Map集合中,需要填基本数据类型包装类
class Solution {
    public int maxConsecutiveAnswers(String answerKey, int k) {
        int left = 0;
        Map<Character, Integer> T_F_dict = new HashMap<>();
        T_F_dict.put('T', 0);
        T_F_dict.put('F', 0);
        char[] answerKeyCharArr = answerKey.toCharArray();
        for(char answer : answerKeyCharArr){
            int answerInt = T_F_dict.get(answer) + 1;
            T_F_dict.put(answer, answerInt);
            if(Math.min(T_F_dict.get('F'), T_F_dict.get('T')) > k){
                int leftInt = T_F_dict.get(answerKeyCharArr[left]) - 1;
                T_F_dict.put(answerKeyCharArr[left], leftInt);
                left++;
            }
        }
        return answerKey.length() - left;
    }
}

执行用时:48 ms, 在所有 Java 提交中击败了6.41%的用户
内存消耗:41.5 MB, 在所有 Java 提交中击败了53.84%的用户

JavaScript

/**
 * @param {string} answerKey
 * @param {number} k
 * @return {number}
 */
var maxConsecutiveAnswers = function(answerKey, k) {
    let [left, dict_T_F] = [0, {"T": 0, "F": 0}]
    for(let answer of answerKey){
        dict_T_F[answer]++
        if(Math.min(dict_T_F["T"], dict_T_F["F"]) > k){
            dict_T_F[answerKey[left]]--
            left++
        }
    }
    return answerKey.length - left
};

执行用时:108 ms, 在所有 JavaScript 提交中击败了25.00%的用户
内存消耗:43.4 MB, 在所有 JavaScript 提交中击败了62.50%的用户

python

class Solution:
    def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
        left, T_F_dict = 0, {"T": 0, "F": 0}
        for answer in answerKey:
            T_F_dict[answer] += 1
            if min(T_F_dict["T"], T_F_dict["F"]) > k:
                T_F_dict[answerKey[left]] -= 1
                left += 1
        return len(answerKey) - left

执行用时:228 ms, 在所有 Python3 提交中击败了92.17%的用户
内存消耗:15.2 MB, 在所有 Python3 提交中击败了72.17%的用户

C

int min(int a, int b){
    return a < b ? a : b;
}

int maxConsecutiveAnswers(char * answerKey, int k){
    int left = 0, countTF[2] = {0, 0}, answerKeyLen = strlen(answerKey);
    for(int i = 0; i < answerKeyLen; i++){
        if(answerKey[i] == 'T') countTF[0]++; //索引0计算T字符个数
        else countTF[1]++; //索引1计算F字符个数
        if(min(countTF[0], countTF[1]) > k){
            if(answerKey[left] == 'T') countTF[0]--;
            else countTF[1]--;
            left++;
        }
    }
    return answerKeyLen - left;
}

执行用时:12 ms, 在所有 C 提交中击败了87.50%的用户
内存消耗:6.5 MB, 在所有 C 提交中击败了91.67%的用户

你可能感兴趣的:(leetcode,leetcode,python,java,javascript,C)