File tree Expand file tree Collapse file tree 4 files changed +62
-4
lines changed Expand file tree Collapse file tree 4 files changed +62
-4
lines changed Original file line number Diff line number Diff line change 49
49
50
50
<!-- 这里可写通用的实现逻辑 -->
51
51
52
+ ** 方法一:哈希表**
53
+
54
+ 根据题目描述,我们可以得到如下结论:
55
+
56
+ 如果有 $n$ 个人的能力值相同,每个人有 $n$ 种不同的位置,那么每个人在原位的概率是 $\frac{1}{n}$,那么合起来的期望就是 $1$。
57
+
58
+ 因此,我们只需要统计不同的能力值的个数,即为答案。
59
+
60
+ 时间复杂度 $O(n)$,空间复杂度 $O(n)$。其中 $n$ 为数组 ` scores ` 的长度。
61
+
52
62
<!-- tabs:start -->
53
63
54
64
### ** Python3**
55
65
56
66
<!-- 这里可写当前语言的特殊实现逻辑 -->
57
67
58
68
``` python
59
-
69
+ class Solution :
70
+ def expectNumber (self , scores : List[int ]) -> int :
71
+ return len (set (scores))
60
72
```
61
73
62
74
### ** Java**
63
75
64
76
<!-- 这里可写当前语言的特殊实现逻辑 -->
65
77
66
78
``` 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**
67
103
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
+ }
68
112
```
69
113
70
114
### ** ...**
Original file line number Diff line number Diff line change
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
+ };
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change 1
1
class Solution {
2
2
public int expectNumber (int [] scores ) {
3
3
Set <Integer > s = new HashSet <>();
4
- for (int v : scores ) {
5
- s .add (v );
4
+ for (int x : scores ) {
5
+ s .add (x );
6
6
}
7
7
return s .size ();
8
8
}
9
- }
9
+ }
You can’t perform that action at this time.
0 commit comments