136. Single Number

Problem:

Given a non-empty 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?

Example 1:

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

Example 2:

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

思路1

首先将数组排序,然后判断每个数与前后是否都不相等,如果都不相等则返回。注意首尾的值单独拿出来比较。

Solution I:

int singleNumber(vector& nums) {
    int n = nums.size();
    if (n == 1) return nums[0];
    sort(nums.begin(), nums.end());
    
    if (nums[0] != nums[1]) return nums[0];
    for (int i = 1; i < n-2; i++) {
        if (nums[i] != nums[i-1] && nums[i] != nums[i+1])
            return nums[i];
    }
    return nums[n-1];
}

性能

Runtime: 24 ms  Memory Usage: 9.9 MB

思路2

利用异或的性质:a XOR a = 0,而且异或操作具有可交换性,所以将数组中所有元素进行XOR操作后,剩下的数即为单一的数。

Solution II:

int singleNumber(vector& nums) {
    int ans = 0;
    
    for (int i = 0; i < nums.size(); i++)
        ans ^= nums[i];
    
    return ans;
}

性能

Runtime: 12 ms  Memory Usage: 9.8 MB

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