投简历的时候看到了个刷题网站,http://www.nowcoder.com/527604,就做了一套题,现记录下来。
题目为:
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 class Solution { public int singleNumber(int[] A) { int result = 0; for(int number: A) result = result ^ number; return result; } }
时间: 2024-10-12 02:58:17