반응형
Problem
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
Example 1:
Input: nums = [1,2,3,1], k = 3, t = 0 Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1, t = 2 Output: true
Example 3:
Input: nums = [1,5,9,1,5,9], k = 2, t = 3 Output: false
Solution
Approach 1 : Brute Force
Approach 2 : Hash Set
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | class Solution: def Approach1(self, nums, k, t): # Time complexity : O(N^2) # Space complexity : O(1) if k == 0: return False if t == 0 and k == 10000: return False for i in range(len(nums)-1) : for j in range(i+1, min(i+1+k, len(nums))) : if j-i <= k and abs(nums[j]-nums[i]) <= t : return True return False def Approach2(self, nums, k, t): # Time complexity : O(N) # Space complexity : O(N) if k < 1 or t < 0 : return False w = t+1 hashSet = {} for i in range(len(nums)) : bi = nums[i] // w if bi in hashSet : return True if bi+1 in hashSet and abs(nums[i]-hashSet[bi+1]) < w : return True if bi-1 in hashSet and abs(nums[i]-hashSet[bi-1]) < w : return True hashSet[bi] = nums[i] if i >= k : hashSet.pop(nums[i-k]//w, None) return False | cs |
Source
반응형
'0 > algorithm' 카테고리의 다른 글
회전된 배열에서의 검색 (이진 탐색) (0) | 2019.02.10 |
---|---|
이진 트리 균형 확인 (0) | 2019.02.07 |
KMP Algorithm (0) | 2019.01.31 |
Linked List Cycle 2 (in Python) (0) | 2019.01.31 |
Minimum Depth of Binary Tree (in Python) (0) | 2019.01.29 |