C++ 16ms solution beats 99.30%


  • 0
    C

    This code beats 99.30% solutions.
    I think my code style is not good enough, can somebody help me make my code more elegant?
    Thank you!

    class Solution {
    public:
        bool containsNearbyDuplicate(vector<int>& nums, int k) {
            if (nums.size() == 0)   return false;//if empty
            size_t i,j;
            size_t size = nums.size();
            vector<int> cp = nums;//cp = copy of nums
            vector<int> duplicates;
            sort(cp.begin(), cp.end());//try to find the duplicate ones
            for(i = 1; i < size; i++){
                if (cp[i - 1] == cp[i])
                    duplicates.push_back(cp[i]);//record the duplicate ones
            }
            int little = INT_MAX;
            int big = INT_MAX;//initialization
            for (i = 0; i < duplicates.size(); i++){//try to find the duplicate element in the nums
                for (j = 0; j < size; j++){
                    if (duplicates[i] == nums[j]){
                        little = big;
                        big = j;
                        if (little != INT_MAX && (big - little) <= k){//only when the two element is close enough
                            return true;
                        }
                    }
                }
    			little = INT_MAX;//reinitialization
    			big = INT_MAX;
            }
            return false;
        }
    };
    

Log in to reply
 

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