136. Single Number

来源:互联网 发布:足球鞋淘宝店 编辑:程序博客网 时间:2024/06/05 21:03

Problem Statement

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?

Thinking

哇,这个问题一开始怎么也没想到用异或(XOR)来做,在一个数组中其他的数字都是成对出现,要找出唯一一个是单个出现的。

异或:0^0 = 0,1^1 = 0,0 ^1 = 1 也就是说相同的异或结果是0,唯一一个没有相同的会返回他本身。

Solution

class Solution {    public int singleNumber(int[] nums) {        int fin = 0;        for(int i = 0;i < nums.length;i++){            fin ^= nums[i];        }        return fin;    }}
原创粉丝点击