[Leetcode]220. Contains Duplicate III

This is Leetcode 220 questions, given an array of integers, ask whether there is gap between the two numbers up to \ (t \) , interval number two at most \ (k \) .
Clearly, there is a need to use a size \ (K \) of the window, each difference number is determined whether there meet each window \ (<= t \) conditions. Each time for simple judgment, need \ (O (K) \) time complexity, the main loop is the first \ (O (of NK) \) . Then, we have optimized the goal is, how in the \ (O (1) \) the number of time whether there is a window to meet the conditions of judgment.
This uses hash Map of thinking, more precisely, a bucket sort of thinking. Each number \ (n-\) is mapped to the \ (n // t \) on the key, if \ (T \) is equal to zero, it is the \ (n-\) itself, each determined \ (key-1 \) and \ (key + 1 \) above to the number. Specific code as follows:

class Solution:
    def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
        n=len(nums)
        if t==0 and n==len(set(nums)):
            return False
        dic = {}
        for i, v in enumerate(nums):
            # t == 0 is a special case where we only have to check the bucket
            # that v is in.
            key, offset = (v // t, 1) if t else (v, 0)
            for idx in range(key - offset, key + offset + 1):
                if idx in dic and abs(dic[idx] - nums[i]) <= t:
                    return True

            dic[key] = v
            if i >= k:
                # Remove the bucket which is too far away. Beware of zero t.
                del dic[nums[i - k] // t if t else nums[i - k]]

        return False

Use Space to reduce the time complexity is a very common routine of. But more often, we need to think about the following use of space to record more information to help us eliminate interference and reduce the time complexity.

Extended :

[Leetcode] 164. Maximum Gap maximum distance

After seeking a disorderly array sorting minimum gap of several adjacent, if based on a comparison of the sort is definitely \ (O (nlogn) \) is. Use the bucket in this question is a natural advantage, the largest gap occurs between max is certainly a valid bucket after bucket of a valid min and before, do not have to compare the size of the barrel elements.
Specific code as follows:

class Solution:
    def maximumGap(self, nums: List[int]) -> int:
        if len(nums) <= 1 :
            return 0

        minValue = 2**31-1
        maxValue = -2**31
        for num in nums:
            minValue = min(minValue, num)
            maxValue = max(maxValue, num)

        bucket_range = (maxValue - minValue) // len(nums) + 1
        bucket_num = ((maxValue - minValue) // bucket_range) + 1

        hashmapMax = {}
        hashmapMin = {}
        for i in range(len(nums)):
            bucket_id = (nums[i]-minValue) // bucket_range
            if not bucket_id in hashmapMax:
                hashmapMax[bucket_id] = nums[i]
                hashmapMin[bucket_id] = nums[i]
            else:

                hashmapMax[bucket_id] = max(hashmapMax[bucket_id],nums[i])
                hashmapMin[bucket_id] = min(hashmapMin[bucket_id],nums[i])

        prev = 0
        res = 0

        for i in range(1,bucket_num):
            if not i in hashmapMax:
                continue
            if not prev in hashmapMax:
                continue
            res = max(res, hashmapMin[i] - hashmapMax[prev])
            prev = i
        return res

[Leetcode] 128. Longest Consecutive Sequence longest contiguous sequence

To a given integer array unsorted, to find the length of the longest contiguous sequence. Required time complexity of the algorithm \ (O (n-) \) . Map storage elements using nums [i] values and the length of its continuous sequence, in which case only two basic cases:

  • Array element appeared nums [i] -1 or nums [i] +1, meaning that the current elements can be grouped into the left or right sequence, then the time length of the sequence if the left and right, respectively left, right, then clearly the nums added [ i], the length of the whole sequence of which is 1 + left + right, and because of this the whole sequence, may only extend around both ends, it is only necessary to update the value of the value of the left and right ends.
  • Has not been seen in the array of elements nums [i] -1 or nums [i] +1, meaning a continuous sequence of the current element is located itself (only own one element).
    Also, note that you can go heavy
class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        nums_set = set(nums)
        dic = {}
        res = 0
        for num in nums_set:
            left = dic.get(num-1,0)
            right = dic.get(num+1,0)
            cur = left+right+1

            dic[num-left] = cur
            dic[num+right] = cur
            res = max(res,cur)
        return res

Guess you like

Origin www.cnblogs.com/hellojamest/p/11617441.html