Skip to content

Commit 8dba54b

Browse files
committed
0528 solved.
1 parent fa268f4 commit 8dba54b

File tree

3 files changed

+52
-0
lines changed

3 files changed

+52
-0
lines changed
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
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})
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
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+
}

readme.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -316,6 +316,8 @@ email: [liuyubobobo@gmail.com](mailto:liuyubobobo@gmail.com)
316316
| 518 | [Coin Change 2](https://leetcode.com/problems/coin-change-2/description/) | [] | [C++](0518-Coin-Change-2/cpp-0518/) | | |
317317
| 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/) | | |
318318
| | | | | | |
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+
| | | | | | |
319321
| 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/) | |
320322
| | | | | | |
321323
| 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/) | | |

0 commit comments

Comments
 (0)