程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Leetcode[1748] and python3 implementation of unique elements (one traverse, two collections)

編輯:Python
# Give you an array of integers nums . The only elements in an array are those that only appear Exactly Once The elements of . 
# 
# Please return nums The only element of and . 
# 
# 
# 
# Example 1: 
# 
# Input :nums = [1,2,3,2]
# Output :4
# explain : The only element is [1,3] , And for 4 .
# 
# 
# Example 2: 
# 
# Input :nums = [1,1,1,1,1]
# Output :0
# explain : There is no single element , And for 0 .
# 
# 
# Example 3 : 
# 
# Input :nums = [1,2,3,4,5]
# Output :15
# explain : The only element is [1,2,3,4,5] , And for 15 .
# 
# 
# 
# 
# Tips : 
# 
# 
# 1 <= nums.length <= 100 
# 1 <= nums[i] <= 100 
# 
# Related Topics Array Hashtable Count 23 0
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def sumOfUnique(self, nums: List[int]) -> int:
ss = set()
ss2 = set()
ret = 0
for num in nums:
if num not in ss2:
if num not in ss:
ss.add(num)
ret += num
else:
ret -= num
ss2.add(num)
return ret
# leetcode submit region end(Prohibit modification and deletion)

Add up each element one by one ;

The first set records elements that have already appeared once , Encounter this element again , Need to remove from the accumulation ;

The second set records elements that have appeared twice , Encounter this element again , Just skip .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved