Single Number

Problem

Given an array of integers, every element appears twice except for one. Find that single one.

Solution

 可用嵌套循环暴力求解,时间复杂度为O(n2)。
 用异或运算巧解,时间复杂度为O(n)。

class Solution {
public:
    int singleNumber(vector& nums) {
        int result = 0;
        for (int i = 0; i < nums.size(); i++){
            result ^= nums[i];
        }
        return result;
    }
};

 原理:输入数组 [4, 2, 4, 1, 2, 3, 3]
 运算等同于 (2 ^ 2) ^ (3 ^ 3) ^ (4 ^ 4) ^ 1 = 0 ^ 0 ^ 0 ^ 1 = 1

你可能感兴趣的:(Single Number)