136. Single Number(python+cpp)

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

解释:
数组中只有一个数字只出现了一次,其他数字则出现了两次,求出这个数字,用Counter()自然可以解,但是从这道题目学到的是奇技淫巧是位运算,将数组中的所有数字都异或一遍最后剩下的即为所求,因为数字和它本身异或的结果是0,任何数和0异或的结果是任何数,初始的值初始化为0,因为0和任何数异或不影响结果。

python代码:

class Solution(object):
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return reduce(lambda x,y:x^y,nums)

c++代码:

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

ps.合理使用set()函数和sum()函数来求这类题目:
python代码:

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

结论:
学会使用位运算,这里学会了异或的特性。
学会使用python中的reduce()函数和lambda表达式。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值