136. Single Number Difficulty: Medium

来源:互联网 发布:最终幻想14 mac 编辑:程序博客网 时间:2024/06/19 05:27

Given an 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?

算法分析aba=b,每个都去异或,那么最后得到的数就是那个孤立的数。

C语言版

int singleNumber(int* nums, int numsSize) {    int i, n = nums[0];    for(i = 1; i < numsSize; i++)        n ^= nums[i];    return n;}

Python版

class Solution(object):    def singleNumber(self, nums):        """        :type nums: List[int]        :rtype: int        """        n = nums[0]        for t in nums[1:]:            n ^= t        return n
原创粉丝点击