Leetcode 697

#697 Degree of an Array

虽然思路差不多,但是代码值得斟酌

int cnt[50000];

class Solution {
public:
    int findShortestSubArray(vector<int>& a) {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);
        memset(cnt, 0, sizeof(cnt));

        for (auto &x: a) {
            cnt[x]++;
        }
        
        int max_time = INT_MIN;
        for (auto &x: a) {
            max_time = max(max_time, cnt[x]);
        }
        
        if (1 == max_time) {
            return 1;
        }
        
        unordered_map<int,pair<int,int>> rec;
        for (int i = 0; i < a.size(); i++) {
            const int v = a[i];
            if (cnt[v] == max_time) {
                auto iter = rec.find(v);
                if (iter != rec.end()) {
                    iter->second.second = i;
                } else {
                    rec.emplace(v, pair<int,int>(i,i));
                }
            }
        }
        
        int min_dist = INT_MAX;
        for (auto &p: rec) {
            min_dist = min(min_dist, p.second.second - p.second.first);
        }
        
        return min_dist + 1;
    }
};

我自己的:

class Solution {
public:
    int findShortestSubArray(vector<int>& nums) {
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout.tie(NULL);
        int N = nums.size();
        if(N <= 1)
            return N;
        std::map<int, int> early;
        std::map<int, int> late;
        std::map<int, int> count;
        vector<int> maxnum;
        int maxcount = INT_MIN;
        for(int i=0; i<N; i++){
            if(early.find(nums[i]) == early.end())
                early[nums[i]] = i;
            late[nums[i]] = i;
            if(count.find(nums[i]) == count.end()){
                count[nums[i]] = 1;
            } else {
                count[nums[i]] += 1;
            }
            if(count[nums[i]] == maxcount){
                maxnum.push_back(nums[i]);
            } else if(count[nums[i]] > maxcount){
                maxcount = count[nums[i]];
                maxnum.clear();
                maxnum.push_back(nums[i]);
            }
        }
        int degree = INT_MAX;
        for(auto i: maxnum){
            //cout << i<<endl;
            if(late[i] - early[i]<degree)
                degree = late[i] - early[i];
                
        }
        return degree + 1;
    }
};

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值