[LeetCode]Single Number

来源:互联网 发布:java编写倒99乘法表 编辑:程序博客网 时间:2024/06/16 21:50

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

Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?

一个整数数组,除了一个数是唯一的,其他都是出现两次,找出这个唯一的数。需求是O(n)的时间复杂度。


解法一:空间复杂度为O(n),遍历数组,用一个hash_set记录每一个数,重复即删除,最后剩下的就是唯一的数。

int singleNumber(vector<int>& nums) {unordered_set<int> setCheck;for (auto it = nums.begin(); it != nums.end(); it++){if (setCheck.count(*it))setCheck.erase(*it);elsesetCheck.insert(*it);}return *(setCheck.begin());}

解法二:最优解,没用额外的内存,利用异或的以下特性:

A^A = 0

0^A = A

A^B = B^A

推导出 A^B^A = A^A^B = 0^B = B

由此可知,异或所有的数即可得出唯一的数

int singleNumber(int* nums, int numsSize) {    int result = 0;    for(int i = 0; i < numsSize; i++)    {        result = result^nums[i];    }    return result;}


0 0
原创粉丝点击