-
-
Notifications
You must be signed in to change notification settings - Fork 291
Expand file tree
/
Copy path398.cpp
More file actions
63 lines (60 loc) · 1.65 KB
/
398.cpp
File metadata and controls
63 lines (60 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
__________________________________________________________________________________________________
sample 40 ms submission
static int x = []() { std::ios::sync_with_stdio(false); cin.tie(NULL); return 0; }();
class Solution{
vector<int>nums;
int size;
public:
Solution(vector<int>nums) {
size = (int)nums.size();
this->nums = move(nums);
};
int pick(int target) const {
if (size) {
const int*pNums = &nums[0], *p = pNums, *pe = p + size;
int count = 0, result = 0;
while (p < pe) {
if (*p == target) {
if (!(rand() % ++count)) { result = (int)(p - pNums); }
}
++p;
}
return result;
}
return -1;
};
};
__________________________________________________________________________________________________
sample 17868 kb submission
class Solution {
vector<int> nums_;
public:
Solution(vector<int> nums)
{
nums_ = move(nums);
}
int pick(int target)
{
int times = 1;
int ret = -1;
for(int i = 0;i < nums_.size();i++)
{
int n = nums_[i];
if(target == n)
{
if(0 == rand() % (times))
{
ret = i;
}
times++;
}
}
return ret;
}
};
/**
* Your Solution object will be instantiated and called as such:
* Solution obj = new Solution(nums);
* int param_1 = obj.pick(target);
*/
__________________________________________________________________________________________________