Skip to content

Commit 11bb188

Browse files
committed
feat: add solutions to lcp problem: No.11
LCP 11.期望个数统计
1 parent e53ead0 commit 11bb188

File tree

4 files changed

+62
-4
lines changed

4 files changed

+62
-4
lines changed

lcp/LCP 11. 期望个数统计/README.md

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,22 +49,66 @@
4949

5050
<!-- 这里可写通用的实现逻辑 -->
5151

52+
**方法一:哈希表**
53+
54+
根据题目描述,我们可以得到如下结论:
55+
56+
如果有 $n$ 个人的能力值相同,每个人有 $n$ 种不同的位置,那么每个人在原位的概率是 $\frac{1}{n}$,那么合起来的期望就是 $1$。
57+
58+
因此,我们只需要统计不同的能力值的个数,即为答案。
59+
60+
时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 `scores` 的长度。
61+
5262
<!-- tabs:start -->
5363

5464
### **Python3**
5565

5666
<!-- 这里可写当前语言的特殊实现逻辑 -->
5767

5868
```python
59-
69+
class Solution:
70+
def expectNumber(self, scores: List[int]) -> int:
71+
return len(set(scores))
6072
```
6173

6274
### **Java**
6375

6476
<!-- 这里可写当前语言的特殊实现逻辑 -->
6577

6678
```java
79+
class Solution {
80+
public int expectNumber(int[] scores) {
81+
Set<Integer> s = new HashSet<>();
82+
for (int x : scores) {
83+
s.add(x);
84+
}
85+
return s.size();
86+
}
87+
}
88+
```
89+
90+
### **C++**
91+
92+
```cpp
93+
class Solution {
94+
public:
95+
int expectNumber(vector<int>& scores) {
96+
unordered_set<int> s(scores.begin(), scores.end());
97+
return s.size();
98+
}
99+
};
100+
```
101+
102+
### **Go**
67103
104+
```go
105+
func expectNumber(scores []int) int {
106+
s := map[int]struct{}{}
107+
for _, x := range scores {
108+
s[x] = struct{}{}
109+
}
110+
return len(s)
111+
}
68112
```
69113

70114
### **...**
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
class Solution {
2+
public:
3+
int expectNumber(vector<int>& scores) {
4+
unordered_set<int> s(scores.begin(), scores.end());
5+
return s.size();
6+
}
7+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
func expectNumber(scores []int) int {
2+
s := map[int]struct{}{}
3+
for _, x := range scores {
4+
s[x] = struct{}{}
5+
}
6+
return len(s)
7+
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
class Solution {
22
public int expectNumber(int[] scores) {
33
Set<Integer> s = new HashSet<>();
4-
for (int v : scores) {
5-
s.add(v);
4+
for (int x : scores) {
5+
s.add(x);
66
}
77
return s.size();
88
}
9-
}
9+
}

0 commit comments

Comments
 (0)