<p>Given an integer array <code>nums</code> and an integer <code>k</code>, return <code>true</code> <em>if there are two <strong>distinct indices</strong> </em><code>i</code><em> and </em><code>j</code><em> in the array such that </em><code>nums[i] == nums[j]</code><em> and </em><code>abs(i - j) &lt;= k</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,1], k = 3
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,0,1,1], k = 1
<strong>Output:</strong> true
</pre>

<p><strong class="example">Example 3:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,2,3,1,2,3], k = 2
<strong>Output:</strong> false
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>-10<sup>9</sup> &lt;= nums[i] &lt;= 10<sup>9</sup></code></li>
	<li><code>0 &lt;= k &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        vector<int> a = nums;
        sort(a.begin(),a.end());
        int lap = a[0];
        vector<int> trungs;
        bool nhap = false;
        for(int i = 1; i < a.size();i++)
        {
            if(a[i] == lap && !nhap)
            {
                trungs.push_back(a[i]);
                nhap = true;
            }
            else
            {
                lap = a[i];
                nhap = false;
            }
        }
        for(int trung:trungs)
        {
            int i = -1;
            int j = -1;
            for(int h = 0;h < nums.size();h++)
            {
                if(nums[h] == trung)
                {
                    if(i == -1) { i = h; }
                    else if(j == -1)
                    {
                        j = h;
                        if((j-i) <= k)
                        {
                            return true;
                        }
                    }
                    else
                    {
                        i = j;
                        j = h;
                        if((j-i) <= k)
                        {
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }
};
68163