forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request soapyigu#362 from soapyigu/SlidingWindow
Build a sliding window solutions set and add a solution to the Longes…
- Loading branch information
Showing
7 changed files
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,41 @@ | ||
/** | ||
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/ | ||
* Primary idea: Slding window, use max and min queues to track largest difference along the way. Move left pointer to get the potential result. | ||
* | ||
* Note: k may be invalid, mention that with interviewer | ||
* Time Complexity: O(n), Space Complexity: O(n) | ||
* | ||
*/ | ||
|
||
class LongestContinuousSubarrayLimit { | ||
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int { | ||
var maxQueue = [Int](), minQueue = [Int](), left = 0, size = 0 | ||
|
||
for (i, num) in nums.enumerated() { | ||
while !maxQueue.isEmpty && maxQueue.last! < num { | ||
maxQueue.removeLast() | ||
} | ||
while !minQueue.isEmpty && minQueue.last! > num { | ||
minQueue.removeLast() | ||
} | ||
|
||
maxQueue.append(num) | ||
minQueue.append(num) | ||
|
||
if maxQueue.first! - minQueue.first! > limit { | ||
if nums[left] == maxQueue.first! { | ||
maxQueue.removeFirst() | ||
} | ||
if nums[left] == minQueue.first! { | ||
minQueue.removeFirst() | ||
} | ||
|
||
left += 1 | ||
} | ||
|
||
size = max(size, i - left + 1) | ||
} | ||
|
||
return size | ||
} | ||
} |
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.