File tree 4 files changed +67
-6
lines changed
solution/1700-1799/1748.Sum of Unique Elements
4 files changed +67
-6
lines changed Original file line number Diff line number Diff line change 42
42
<li><code>1 <= nums[i] <= 100</code></li>
43
43
</ul >
44
44
45
-
46
45
## 解法
47
46
48
47
<!-- 这里可写通用的实现逻辑 -->
49
48
49
+ 定义一个计数器 counter,存放数组每个元素出现的次数。
50
+
51
+ 然后遍历 counter 中每个元素,累加次数为 1 的所有下标即可。
52
+
50
53
<!-- tabs:start -->
51
54
52
55
### ** Python3**
53
56
54
57
<!-- 这里可写当前语言的特殊实现逻辑 -->
55
58
56
59
``` python
57
-
60
+ class Solution :
61
+ def sumOfUnique (self , nums : List[int ]) -> int :
62
+ counter = [0 ] * 101
63
+ for num in nums:
64
+ counter[num] += 1
65
+ return sum ([i for i in range (1 , 101 ) if counter[i] == 1 ])
58
66
```
59
67
60
68
### ** Java**
61
69
62
70
<!-- 这里可写当前语言的特殊实现逻辑 -->
63
71
64
72
``` java
65
-
73
+ class Solution {
74
+ public int sumOfUnique (int [] nums ) {
75
+ int [] counter = new int [101 ];
76
+ for (int num : nums) {
77
+ ++ counter[num];
78
+ }
79
+ int res = 0 ;
80
+ for (int i = 1 ; i < 101 ; ++ i) {
81
+ if (counter[i] == 1 ) {
82
+ res += i;
83
+ }
84
+ }
85
+ return res;
86
+ }
87
+ }
66
88
```
67
89
68
90
### ** ...**
Original file line number Diff line number Diff line change 41
41
<li><code>1 <= nums[i] <= 100</code></li>
42
42
</ul >
43
43
44
-
45
44
## Solutions
46
45
47
46
<!-- tabs:start -->
48
47
49
48
### ** Python3**
50
49
51
50
``` python
52
-
51
+ class Solution :
52
+ def sumOfUnique (self , nums : List[int ]) -> int :
53
+ counter = [0 ] * 101
54
+ for num in nums:
55
+ counter[num] += 1
56
+ return sum ([i for i in range (1 , 101 ) if counter[i] == 1 ])
53
57
```
54
58
55
59
### ** Java**
56
60
57
61
``` java
58
-
62
+ class Solution {
63
+ public int sumOfUnique (int [] nums ) {
64
+ int [] counter = new int [101 ];
65
+ for (int num : nums) {
66
+ ++ counter[num];
67
+ }
68
+ int res = 0 ;
69
+ for (int i = 1 ; i < 101 ; ++ i) {
70
+ if (counter[i] == 1 ) {
71
+ res += i;
72
+ }
73
+ }
74
+ return res;
75
+ }
76
+ }
59
77
```
60
78
61
79
### ** ...**
Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ public int sumOfUnique (int [] nums ) {
3
+ int [] counter = new int [101 ];
4
+ for (int num : nums ) {
5
+ ++counter [num ];
6
+ }
7
+ int res = 0 ;
8
+ for (int i = 1 ; i < 101 ; ++i ) {
9
+ if (counter [i ] == 1 ) {
10
+ res += i ;
11
+ }
12
+ }
13
+ return res ;
14
+ }
15
+ }
Original file line number Diff line number Diff line change
1
+ class Solution :
2
+ def sumOfUnique (self , nums : List [int ]) -> int :
3
+ counter = [0 ] * 101
4
+ for num in nums :
5
+ counter [num ] += 1
6
+ return sum ([i for i in range (1 , 101 ) if counter [i ] == 1 ])
You can’t perform that action at this time.
0 commit comments