LeetCode #219 Contains Duplicate II 存在重復(fù)元素 II

219 Contains Duplicate II 存在重復(fù)元素 II

Description:
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.

Example:

Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true

Example 2:
Input: nums = [1,0,1,1], k = 1
Output: true

Example 3:
Input: nums = [1,2,3,1,2,3], k = 2
Output: false

題目描述:
給定一個(gè)整數(shù)數(shù)組和一個(gè)整數(shù) k,判斷數(shù)組中是否存在兩個(gè)不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的絕對(duì)值最大為 k。

示例:

示例 1:
輸入: nums = [1,2,3,1], k = 3
輸出: true

示例 2:
輸入: nums = [1,0,1,1], k = 1
輸出: true

示例 3:
輸入: nums = [1,2,3,1,2,3], k = 2
輸出: false

思路:

利用 map記錄出現(xiàn)過(guò)的數(shù)字, 如果 map中已經(jīng)存放了這個(gè)數(shù)字, 要么滿足題意輸出 true, 要么更新下標(biāo)值
時(shí)間復(fù)雜度O(n), 空間復(fù)雜度O(k), map中最多記錄 k個(gè)元素

代碼:
C++:

class Solution 
{
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) 
    {
        if (nums.size() < 2) return false;
        map<int,int> temp;
        for (int i = 0; i < nums.size(); i++) 
        {
            if (temp.count(nums[i])) 
            {
                if (i - temp[nums[i]] <= k) return true;
                else temp[nums[i]] = i;
            }
            else temp[nums[i]] = i;
        }
        return false;
    }
};

Java:

class Solution {
    public boolean containsNearbyDuplicate(int[] nums, int k) {
        if (nums.length < 2) return false;
        Map<Integer, Integer> temp = new HashMap<>(k);
        for (int i = 0; i < nums.length; i++) {
            if (temp.containsKey(nums[i])) {
                if (i - temp.get(nums[i]) <= k) return true;
                else temp.put(nums[i], i);
            } else {
                temp.put(nums[i], i);
            }
        }
        return false;
    }
}

Python:

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        if len(nums) < 2:
            return False
        temp = {}
        for i, num in enumerate(nums):
            if num in temp:
                if i - temp[num] <= k:
                    return True
                else:
                    temp[num] = i
            else:
                temp[num] = i
        return False
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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