[LeetCode] Single Number

来源:互联网 发布:关于php的知识 编辑:程序博客网 时间:2024/04/30 07:16

Single Number

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?

解题思路:

解法一:先排序,再遍历。时间复杂度为O(nlogn),空间复杂度为O(1)。代码略。

解法二:用一个set来记录结果,若已经存在,则从set中删除。最终只留下目标数字。时间复杂度为O(n),空间复杂度为O(n)。

解法三:位操作。注意,两个相同数字异或为0,0与任何数字异或等于该数字本身。这样时间复杂度为O(n),空间复杂度为O(1)。

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

0 0
原创粉丝点击