zoukankan      html  css  js  c++  java
  • leetcode 260

    `260. Single Number III
    Medium

    2732

    152

    Add to List

    Share
    Given an integer array nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. You can return the answer in any order.

    You must write an algorithm that runs in linear runtime complexity and uses only constant extra space.

    Example 1:

    Input: nums = [1,2,1,3,2,5]
    Output: [3,5]
    Explanation: [5, 3] is also a valid answer.
    Example 2:

    Input: nums = [-1,0]
    Output: [-1,0]
    Example 3:

    Input: nums = [0,1]
    Output: [1,0]

    Constraints:

    2 <= nums.length <= 3 * 104
    -231 <= nums[i] <= 231 - 1
    Each integer in nums will appear twice, only two integers will appear once.`

    single num 加加强版, 首先先求异或值, 因为两个独特的数字, 所以异或值不为0, 找到不为0的二进制最小位数. 然后对nums中所有该位不为0的数字进行与或求得其中一个数的值

    `class Solution:
    def singleNumber(self, nums: List[int]) -> List[int]:
    xor_result = 0
    for i in nums:
    xor_result ^= i

        pos = -1
        for i in range(128):
            if (xor_result & 1 << i) == 1 << i:
                pos = i
                break
        else:
            raise Exception
        
        x = 0
        for i in nums:
            if (i & 1 << pos) == 1 << pos:
                x ^= i
        y = xor_result ^ x
        return [x, y]`
  • 相关阅读:
    最精简的django程序
    spring+mongo
    从零搭建mongo分片集群的简洁方法
    java对redis的基本操作
    awk输出指定列
    sed输出指定行
    Bash的循环结构(for和while)
    用ffmpeg切割音频文件
    Python判断字符串是否全是字母或数字
    Python函数: any()和all()的用法
  • 原文地址:https://www.cnblogs.com/mangmangbiluo/p/15386814.html
Copyright © 2011-2022 走看看