本文共 713 字,大约阅读时间需要 2 分钟。
https://oj.leetcode.com/problems/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?public int singleNumber(int[] A)
这一题最直接的想法必然是HashMap来遍历然后找出唯一只存在过一次的数字。但是这种做法太直观,一看就知道要挂的。。。
好,让我们重新补习一下我们大学学过的数字逻辑。里面有一种操作叫异或。它有一个特性,0^a = a, 还有一个特性, 就是a^a = 0,还有一个特性叫做交换律。就是a^b^c = a^c^b,那么延伸一下就是a^b^a = a^a^b = 0 ^ b = b
孩纸们,复习完了么?可以去考期末了哟。。。。。
咳咳,好吧,说到这里我相信大家应该知道这一题的做法了吧?实际上这一题就是一个bit operation的题目。把所有东西异或一下剩下来的就是我们要找的。代码很简单,就贴一下好了:
public int singleNumber(int[] A) { int res = 0; for(int n : A) res ^= n; return res; }
转载地址:http://wwoxb.baihongyu.com/