219. Contains Duplicate II

Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

給定數(shù)組nums,求里面重復(fù)元素的距離是否最大不超過k。

Solution:

利用HashMap來存nums[i]與其對應(yīng)的index i,這里要注意HashMap里面的更新問題,如果多次重復(fù)出現(xiàn)某個元素,則HashMap里面更新為最新的該元素與index的映射關(guān)系,可能滿足距離小于等于k的兩個nums[i]元素只可能是當(dāng)前這個nums[i]和未來將要遍歷到的nums[i]。
等價于求所有相鄰的nums[i]之間是否存在有小于等于k的距離。

public class Solution 
{
    public boolean containsNearbyDuplicate(int[] nums, int k) 
    {
        HashMap<Integer, Integer> hm = new HashMap<>();
        for(int i = 0; i < nums.length; i ++)
        {
            if(hm.containsKey(nums[i]))
            {
                int preIndex = hm.get(nums[i]);
                if(i - preIndex <= k)
                    return true;
            }
            hm.put(nums[i], i);
        }
        return false;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容