diff options
| author | mo khan <mo.khan@gmail.com> | 2020-08-25 13:18:45 -0600 |
|---|---|---|
| committer | mo khan <mo.khan@gmail.com> | 2020-08-25 13:18:45 -0600 |
| commit | 773f8dfa33535c649279e79bc9cb57c415ee9c62 (patch) | |
| tree | f8c9ef612fba8b908e1506a63e4f655b3cb74f7b | |
| parent | 272b640bf9689981c2e1bef3646be51690acfe94 (diff) | |
Solve in O(nlogn) time
| -rw-r--r-- | 2020/08/24/main.rb | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/2020/08/24/main.rb b/2020/08/24/main.rb index 102cf91..b3742b3 100644 --- a/2020/08/24/main.rb +++ b/2020/08/24/main.rb @@ -20,6 +20,28 @@ class Solution false end + + # time: O(nlogn) + O(n) == O(nlogn) + # space: O(n) + def self.run(items) + h, t = 0, items.size - 1 + items.sort! # nlogn + cache = {} + + until h >= t + head = items[h] ** 2 + tail = items[t] ** 2 + expected = tail - head + return true if cache[expected] + + cache[head] = true + cache[tail] = true + + expected > tail ? t-=1 : h+=1 + end + + nil + end end assert(Solution.run([3, 12, 5, 13])) |
