Go语言实现Find the odd int

描述

Given an array, find the int that appears an odd number of times.
There will always be only one integer that appears an odd number of times.

分析

方法1:遍历数组,借助map保存已遍历过的数据的重复次数。最后遍历map,返回重复次数为奇数的键值。
方法2:因为题目明确数组中重复奇数次数的数据项只有一个,那么其它数据项出现次数是偶数次,这些数据项经过偶数次抑或会变为0,而奇数次数的数据项经过抑或后,结果就是该奇数本身。

实现

方法1:

func FindOdd(seq []int) int {
  dict := map[int]int{}
  for _, v := range seq { dict[v]++ }
  for k, v := range dict {
    if v % 2 == 1 { return k }
  }
  return 0
}

方法2:

func FindOdd(seq []int) (res int) {
    for _, n := range seq {
        res ^= n
    }
    return
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值