双指针 题解 | #最长无重复子数组#

最长无重复子数组

https://www.nowcoder.com/practice/b56799ebfd684fb394bd315e89324fb4

class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param arr int整型vector the array
     * @return int整型
     */
    // 双指针解法 O(n) yyds
    int maxLength(vector<int>& arr) {
        // write code here
        int n = arr.size();
        int ans = 1;
        map<int, int> s;
        for (int i = 0, j = 0; j < n; j++) {
            s[arr[j]]++;
            while (s[arr[j]] >= 2) s[arr[i++]]--;
            ans = max(ans, j - i + 1);
        }
        return ans;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务