【leetcode刷题】T37-存在重复元素 II

这是木又陪伴你的第58html


今天分享leetcode解题第37篇文章,是leetcode第219题—存在重复元素 II(Contains Duplicate II),地址是:https://leetcode-cn.com/problems/contains-duplicate-ii/python

【英文题目】(学习英语的同时,更能理解题意哟~)c++

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 iand j is at most k.数组

Example 1:微信

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

Example 2:app

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

【中文题目】学习

给定一个整数数组和一个整数 k,判断数组中是否存在两个不一样的索引 ij,使得 nums [i] = nums [j],而且 ij 的差的绝对值最大为 kui

示例 1:url

输入: nums = [1,2,3,1], k = 3
输出: true

示例 2:spa

输入: nums = [1,0,1,1], k = 1
输出: true

【思路】

本题与【T36-存在重复元素】相似,两种方法:一是暴力破解,二是使用hash表。

暴力破解:使用两层for循环,查找是否有元素知足条件。

hash表:key为元素,value为元素的下标,当某个元素存在hash表中,则判断是否知足条件,若是不知足,则更新value值。

【代码】

python版本

class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """

        d = {}
        for i, n in enumerate(nums):
            if n in d and i - d[n] <= k:
                return True
            d[n] = i
        return False

C++版本

class Solution {
public:
    bool containsNearbyDuplicate(vector<int>& nums, int k) {
        map<intint> d;
        for(int i=0; i<nums.size(); i++){
            if(d.find(nums[i]) != d.end() && i - d[nums[i]] <= k)
                return true;
            d[nums[i]] = i;
        }
        return false;
    }
};


相关文章:

T36-存在重复元素


给我好看

本文分享自微信公众号 - 木又AI帮(gh_eaa31cab4b91)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。

相关文章
相关标签/搜索