diff --git a/README.md b/README.md index 17cba055..2f75d068 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ ![Leetcode](./logo.png?style=centerme) ## Progress -[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 314 completed solutions. Note: questions with ♥ mark means that you have to **Subscript to premium membership** of LeetCode to unlock them. +[Problem Status](#problem-status) shows the latest progress to all 1000+ questions. Currently we have 315 completed solutions. Note: questions with ♥ mark means that you have to **Subscript to premium membership** of LeetCode to unlock them. ## Contributors @@ -356,6 +356,7 @@ [Search Insert Position](https://leetcode.com/problems/search-insert-position/)| [Swift](./Search/SearchForARange.swift)| Medium| O(logn)| O(1)| [Peak Index in a Mountain Array](https://leetcode.com/problems/peak-index-in-a-mountain-array/)| [Swift](./Search/PeakIndexMountainArray.swift)| Easy| O(logn)| O(1)| [Find Peak Element](https://leetcode.com/problems/find-peak-element/)| [Swift](./Search/FindPeakElement.swift)| Medium| O(logn)| O(1)| +[Random Pick with Weight](https://leetcode.com/problems/random-pick-with-weight/)| [Swift](./Search/RandomPickWeight.swift)| Medium| O(logn)| O(1)| [Sqrt(x)](https://leetcode.com/problems/sqrtx/)| [Swift](./Search/Sqrtx.swift)| Medium| O(logn)| O(1)| [Median of Two Sorted Arrays](https://leetcode.com/problems/median-of-two-sorted-arrays/)| [Swift](./Search/MedianTwoSortedArrays.swift)| Hard| O(log(m + n))| O(1)| [Minimize Max Distance to Gas Station](https://leetcode.com/problems/minimize-max-distance-to-gas-station/)| [Swift](./Search/MinimizeMaxDistanceGasStation.swift)| Hard| O(nlogm)| O(1)| diff --git a/Search/RandomPickWeight.swift b/Search/RandomPickWeight.swift new file mode 100644 index 00000000..797bd85c --- /dev/null +++ b/Search/RandomPickWeight.swift @@ -0,0 +1,50 @@ +/** + * Question Link: https://leetcode.com/problems/random-pick-with-weight/ + * Primary idea: Random select a number from sum of the array, and search the first number + * greater than the number in sums array constructed from the original array. + * + * Time Complexity: O(logn), Space Complexity: O(n) + */ + + +class RandomPickWeight { + + var sums: [Int] + + init(_ w: [Int]) { + sums = w + + for i in 1.. Int { + guard let sum = sums.last else { + return -1 + } + + return findFirstGreaterThan(Int.random(in: 0.. Int { + var left = 0, right = sums.count - 1 + + while left < right { + let mid = (right - left) / 2 + left + if sums[mid] > num { + right = mid + } else { + left = mid + 1 + } + } + + return left + } +} + +/** + * Your Solution object will be instantiated and called as such: + * let obj = Solution(w) + * let ret_1: Int = obj.pickIndex() + */ \ No newline at end of file