File tree Expand file tree Collapse file tree 3 files changed +52
-0
lines changed
0528-Random-Pick-with-Weight/cpp-0528 Expand file tree Collapse file tree 3 files changed +52
-0
lines changed Original file line number Diff line number Diff line change
1
+ cmake_minimum_required (VERSION 3.5 )
2
+ project (cpp_0528 )
3
+
4
+ set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11" )
5
+
6
+ set (SOURCE_FILES main.cpp )
7
+ add_executable (cpp_0528 ${SOURCE_FILES} )
Original file line number Diff line number Diff line change
1
+ // / Source : https://leetcode.com/problems/random-pick-with-weight/description/
2
+ // / Author : liuyubobobo
3
+ // / Time : 2018-08-28
4
+
5
+ #include < iostream>
6
+ #include < vector>
7
+ #include < algorithm>
8
+
9
+ using namespace std ;
10
+
11
+
12
+ // / Pre-Sum and Binary Search
13
+ // / Time Complexity: init: O(n)
14
+ // / pickIndex: O(logn)
15
+ // / Space Complexity: O(n)
16
+ class Solution {
17
+
18
+ private:
19
+ vector<int > sum;
20
+
21
+ public:
22
+ Solution (vector<int > w) {
23
+ sum.clear ();
24
+ sum.push_back (0 );
25
+ for (int e: w)
26
+ sum.push_back (sum.back () + e);
27
+ }
28
+
29
+ int pickIndex () {
30
+
31
+ int randNum = rand () % sum.back ();
32
+ int index = lower_bound (sum.begin (), sum.end (), randNum) - sum.begin ();
33
+ if (sum[index] != randNum)
34
+ index --;
35
+ return index;
36
+ }
37
+ };
38
+
39
+
40
+ int main () {
41
+
42
+ return 0 ;
43
+ }
Original file line number Diff line number Diff line change @@ -316,6 +316,8 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
316
316
| 518 | [ Coin Change 2] ( https://leetcode.com/problems/coin-change-2/description/ ) | [ 无] | [ C++] ( 0518-Coin-Change-2/cpp-0518/ ) | | |
317
317
| 519 | [ Random Flip Matrix] ( https://leetcode.com/problems/random-flip-matrix/description/ ) | [ solution] ( https://leetcode.com/problems/random-flip-matrix/solution/ ) | [ C++] ( 0519-Random-Flip-Matrix/cpp-0519/ ) | | |
318
318
| | | | | | |
319
+ | 528 | [ Random Pick with Weight] ( https://leetcode.com/problems/random-pick-with-weight/description/ ) | [ solution] ( https://leetcode.com/problems/random-pick-with-weight/solution/ ) | [ C++] ( 0528-Random-Pick-with-Weight/cpp-0528/ ) | | |
320
+ | | | | | | |
319
321
| 530 | [ Minimum Absolute Difference in BST] ( https://leetcode.com/problems/minimum-absolute-difference-in-bst/description/ ) | [ 无] | | [ Java] ( 0530-Minimum-Absolute-Difference-in-BST/java-0530/src/ ) | |
320
322
| | | | | | |
321
323
| 541 | [ Reverse String II] ( https://leetcode.com/problems/reverse-string-ii/description/ ) | [ solution] ( https://leetcode.com/problems/reverse-string-ii/solution/ ) | [ C++] ( 0541-Reverse-String-II/cpp-0541/ ) | | |
You can’t perform that action at this time.
0 commit comments