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

最长无重复子数组

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

//双指针法+hash
//首先判断arr
//其次right指针右移,且值一直进入mp
//如果某一个mp(右指针的值)的值>1,则left左移,mp(left)--
#include <algorithm>
#include <unordered_map>
#include <vector>
class Solution {
public:
    /**
     * 
     * @param arr int整型vector the array
     * @return int整型
     */
    int maxLength(vector<int>& arr) {
        // write code here
        if (arr.size()==0) {
            return 0;
        }
        int res=0;
        unordered_map<int, int> mp;
        int left=0,right=0;
        for (; right<arr.size(); right++) {
            mp[arr[right]]++;
            while (mp[arr[right]]>1) {
                mp[arr[left++]]--;
            }
            res=max(res, right-left+1);
        }
        return res;
    }
};

全部评论

相关推荐

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