Giả sử ta có mảng nums với một số phần tử trùng lặp và một số phần tử duy nhất. Ta phải tìm tổng của tất cả các phần tử duy nhất có mặt trong nums.
Ví dụ: nums = [5,2,1,5,3,1,3,8], kết quả là 10 vì chỉ có 8 và 2 là duy nhất, tổng = 10.
Giải thuật
count := Counter(nums)(tần suất mỗi phần tử)ans := 0- Với mỗi
index, valuetrongnums:- Nếu
count[value] == 1:ans += value
- Nếu
- Trả về
ans
Ví dụ (Python)
from collections import Counter
def solve(nums):
count = Counter(nums)
ans = 0
for index, value in enumerate(nums):
if count[value] == 1:
ans += value
return ans
nums = [5, 2, 1, 5, 3, 1, 3, 8]
print(solve(nums))
Input
[5,2,1,5,3,1,3,8]
Output
10