Skip to content

Latest commit

 

History

History
49 lines (48 loc) · 2.09 KB

数组中数字出现的次数.org

File metadata and controls

49 lines (48 loc) · 2.09 KB

260. 只出现一次的数字 III

题目

Screen-Pictures/%E9%A2%98%E7%9B%AE/2020-07-04_11-51-11_%E6%88%AA%E5%B1%8F2020-07-04%20%E4%B8%8A%E5%8D%8811.51.08.png

思路

https://leetcode-cn.com/problems/shu-zu-zhong-shu-zi-chu-xian-de-ci-shu-lcof/solution/jie-di-qi-jiang-jie-fen-zu-wei-yun-suan-by-eddievi/

code

class Solution:
    def singleNumbers(self, nums: List[int]) -> List[int]:
        k = 0
        for n in nums:
            k ^= n
        mask = 1
        while (k & mask==0):
            mask <<= 1
        a, b = 0, 0
        for n in nums:
            if n & mask == 0:
                a ^= n
            else:
                b ^= n
        return [a, b]

136. 只出现一次的数字

题目

Screen-Pictures/136._%E5%8F%AA%E5%87%BA%E7%8E%B0%E4%B8%80%E6%AC%A1%E7%9A%84%E6%95%B0%E5%AD%97/2020-07-23_17-35-53_%E6%88%AA%E5%B1%8F2020-07-23%20%E4%B8%8B%E5%8D%885.35.52.png

思路

  • 异或运算:a^a=0,因此全部元素异或一遍,最后的结果就是只出现一次的元素

code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        ans = 0
        for num in nums:
            ans ^= num
        return ans

137. 只出现一次的数字 II

题目

Screen-Pictures/137._%E5%8F%AA%E5%87%BA%E7%8E%B0%E4%B8%80%E6%AC%A1%E7%9A%84%E6%95%B0%E5%AD%97_II/2020-07-23_17-37-23_%E6%88%AA%E5%B1%8F2020-07-23%20%E4%B8%8B%E5%8D%885.37.21.png

思路

  • 位运算:

code