LeetCode六月挑战(6.22 )Single Number II LeetCode 137解题方案
Given a non-empty array of integers, every element appears three times except for one, which appears exactly once. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
Example 1:
Input: [2,2,3,2]
Output: 3
Example 2:
Input: [0,1,0,1,0,1,99]
Output: 99
思路
将 数组中的数据放入Set中,然后让Set中的元素都出现三次,然后减去nums中元素的总和,这样,最后的结果为两倍数组中只出现一次的元素,最后返回1/2的结果即可。
代码
class Solution:
def singleNumber(self, nums: List[int]) -> int:
return (3*sum(set(nums))-sum(nums))//2