LeetCode刷题之一:寻找只出现一次的数字

来源:互联网 发布:淘宝微淘的好处 编辑:程序博客网 时间:2024/06/09 17:38

投简历的时候看到了个刷题网站,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;    }}


1 0
原创粉丝点击