zoukankan      html  css  js  c++  java
  • [LeetCode] 136. Single Number 单独数

    Given a non-empty array of integers, every element appears twice except for one. 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,1]
    Output: 1
    

    Example 2:

    Input: [4,1,2,1,2]
    Output: 4

    由于要求时间复杂度O(n),空间复杂度O(1),所以不能用排序法,也不能使用map。

    解法1:用两倍所有非重复元素和减去原数组。

    解法2:位操作Bit Operation,使用二进制数位操作中的异或,同为0,异为1。主要考察位操作。

    异或运算{displaystyle Aoplus B}Aoplus B的真值表如下: F表示false,T表示true 

     
    AB
    F F F
    F T T
    T F T
    T T F

    Java:

    public class Solution {
        public int singleNumber(int[] nums) {
            int res = 0;
            for (int num : nums) res ^= num;
            return res;
        }
    }
    

    Python:

    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return 2 * sum(set(nums)) - sum(nums)  

    Python:

    class Solution(object):
        def singleNumber(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            res = 0
            for num in nums:
                res ^= num
                
            return res  

    Python:

    import operator
    from functools import reduce
    
    class Solution:
        """
        :type nums: List[int]
        :rtype: int
        """
        def singleNumber(self, A):
            return reduce(operator.xor, A)  

    C++:

    class Solution {
    public:
        int singleNumber(vector<int>& nums) {
            int res = 0;
            for (auto num : nums) res ^= num;
            return res;
        }
    };
    

    类似题目:

    [LeetCode] 137. Single Number II 单独数 II

    [LeetCode] 260. Single Number III 单独数 III

    All LeetCode Questions List 题目汇总

      

  • 相关阅读:
    神经网络加速与模型压缩
    字符串分割函数
    物体检测整理
    deeplab算法解析
    kmeans算法
    封装caffe版的deeplab为库供第三方使用
    进程 守护
    socketserver tcp黏包
    计算机
    网络 协议 2
  • 原文地址:https://www.cnblogs.com/lightwindy/p/9680430.html
Copyright © 2011-2022 走看看