[LeetCode By Go 16]136. Single Number

题目

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?

中文大意

给定一个整数数组,里面只有一个数只出现一次,其余的数都出现两次,找出只出现一次的数。

解题思路

采用异或运算^
a ^ a = 0
a ^ 0 = a
a ^ b ^ c = a ^ (b ^ c)
因此所有数进行异或,最终得到的就是只出现一次的数

代码

func singleNumber(nums []int) int {
    var ret int
    ret = 0
    for _,v := range nums {
        ret = ret ^ v
    }
    return ret
}
    原文作者:miltonsun
    原文地址: https://www.jianshu.com/p/c9e0141a92cb
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞