5 line Java code solution


  • 5
    E
    public boolean containsNearbyDuplicate(int[] nums, int k) {
            Set<Integer> set = new HashSet<Integer>();
    
            for(int j = 0; j < nums.length; j++){
                if(j > k) set.remove(nums[j - k - 1]);
                if(!set.add(nums[j]))  return true;
            }
            return false;
    }

  • 0
    D

    class Solution {
    public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
    if(nums.size()==0||nums.size()==1)
    {
    return false;
    }
    vector<int> tmp=nums;
    sort(nums.begin(),nums.end());
    for(int i=0;i<nums.size()-1;i++)
    {
    if(nums[i]==nums[i+1])
    {
    for(int j=0;j<tmp.size();j++)
    {
    if(nums[i]==tmp[j])
    {
    for(int m=j+1;m<tmp.size();m++)
    {
    if((tmp[j]==tmp[m])&&((m-j)<=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.