24 ms solution using vector of pairs


  • 0
    A
    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            vector<pair<int, int> > vi;
            for(int i = 0; i < nums.size(); i++){
                vi.push_back(make_pair(nums[i], i));
            }
            sort(vi.begin(), vi.end());
            for(int i = 0; i < vi.size(); i++){
                if(vi[i].first == vi[i + 1].first){
                    if(vi[i + 1].second - vi[i].second <= k){
                        return true;
                    }
                }
            }
            return false;
        }
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.