【leetcode】219. Contains Duplicate II(Python & C++)

来源:互联网 发布:pdg文件在mac 编辑:程序博客网 时间:2024/06/02 03:50

219. Contains Duplicate II

题目链接

219.1 题目描述:

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.

219.2 解题思路:

  1. 思路一:简单的两层循环,外循环i从0到nums.size-1,内循环j从i+1到j小于nums.size() && j 小于等于 i + k,然后判断是否有相等的即可,有则返回true。循环结束,返回false。

  2. 思路二:利用mapint,int>映射。循环nums,如果m[nums[i]]的值不为0,说明此时nums[i]跟前民有重复的,并且如果(i - m[nums[i]] + 1) 小于 k,说明二者坐标之间的间距没有超过k,则返回true。然后将m[nums[i]]存放其坐标i+1,之所以不是i,为了避免跟前面判断混淆。循环结束,返回false。

  3. 思路三:分为C++和Python。

    • C++:利用set。而且set始终维持不大于k个元素。循环nums,如果i>k,说明此时长度超多k了,即使相等也无意义了,将set中nums[i - k - 1]元素移除。然后寻找s.find(nums[i]) != s.end(),这表示nums[i]是否在set中,若在,则说明符合题意,返回true。然后将nums[i]插入s中。循环结束,返回false。

    • python:利用enumerate(nums),不过思想还是跟思路二一样,不做赘述。

219.3 C++代码:

1、思路一代码(超时):

class Solution113 {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        //超时        if (nums.size() <2)            return false;        for (int i = 0; i < nums.size();i++)        {            for (int j = i + 1; j<nums.size() && j <= i + k;j++)            {                if (nums[i] == nums[j])                    return true;            }        }        return false;    }};

2、思路二代码(52ms):

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

3、思路三代码(45ms)

class Solution113_2 {public:    bool containsNearbyDuplicate(vector<int>& nums, int k) {        if (nums.size() < 2)            return false;        set<int>s;        for (int i = 0; i < nums.size();i++)        {            if (i>k)                s.erase(nums[i - k - 1]);            if (s.find(nums[i]) != s.end())                return true;            s.insert(nums[i]);        }        return false;    }};

219.4 Python代码:

1、思路二代码(46ms)

class Solution(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        if len(nums)<2:            return False        d={}        for i in range(len(nums)):            if nums[i] in d and (i-d[nums[i]]) <= k:                return True            d[nums[i]]=i        return False

2、思路三代码(46ms)

class Solution1(object):    def containsNearbyDuplicate(self, nums, k):        """        :type nums: List[int]        :type k: int        :rtype: bool        """        d={}        for key,value in enumerate(nums):            if value in d and key-d[value] <= k:                return True            d[value]=key        return False

原创粉丝点击