算法18-----判断是否存在符合条件的元素【list】

1、题目:

给定一个整数数组,判断其中是否存在两个不同的下标i和j满足:| nums[i] - nums[j] | <= t 并且 | i - j | <= k

2、思路:

 

来自链接:http://bookshadow.com/weblog/2015/06/03/leetcode-contains-duplicate-iii/

3、代码:

    def containsNearbyAlmostDuplicate(self, nums, k, t):
        """
        :type nums: List[int]
        :type k: int
        :type t: int
        :rtype: bool
        """
        if k < 1 or t < 0:
            return False
        dic = collections.OrderedDict()
        for n in nums:
            key = n if not t else n // t
            for m in (dic.get(key - 1), dic.get(key), dic.get(key + 1)):
                if m is not None and abs(n - m) <= t:
                    return True
            if len(dic) == k:
                dic.popitem(False)
            print(key,n)
            dic[key] = n
        return False

 

posted on 2018-05-16 10:34  吱吱了了  阅读(352)  评论(0编辑  收藏  举报

导航