Find the number of a single digit

Title description:

Given a set of numbers, find the number of a single number from it

输入:[2,2,1]
输出:1

Problem-solving ideas:

  1. Calculate the elements in the array and the number of occurrences by Counter;
  2. Traverse the keys that appear and find whether the corresponding value is 1;
  3. After finding it, just output the subscript;

Code:

from collections import Counter
class Solution:
    def singleNumber(self, nums):
        hashmap = Counter(nums)
        for k in hashmap.keys():
            if hashmap[k] == 1:
                return k

s = Solution()
nums = [2, 2, 1]
print(s.singleNumber(nums))

Guess you like

Origin blog.csdn.net/weixin_43283397/article/details/110820181