Single Number

281 阅读1分钟

date: 2018/09/19 原文


1. Question

Given a non-empty array of integers, every element appears twice except for one. Find that single one.

Example 1:

Input: [2,2,1]
Output: 1

Example 2:

Input: [4,1,2,1,2]
Output: 4

2. Solution

class Solution {
    public int singleNumber(int[] nums) {
        int i = 1;
        int a = nums[0];
        while (i < nums.length) {
            a = a ^ nums[i];  //利用与或的关系
            i++;
        }
        return a;
    }
}

3. Think

思路: 利用java中与或关系,进行运算最优