跳转至

136. 只出现一次的数字

题目描述

给你一个 非空 整数数组 nums ,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

你必须设计并实现线性时间复杂度的算法来解决此问题,且该算法只使用常量额外空间。

 

示例 1 :

输入:nums = [2,2,1]
输出:1

示例 2 :

输入:nums = [4,1,2,1,2]
输出:4

示例 3 :

输入:nums = [1]
输出:1

 

提示:

  • 1 <= nums.length <= 3 * 104
  • -3 * 104 <= nums[i] <= 3 * 104
  • 除了某个元素只出现一次以外,其余每个元素均出现两次。

解法

方法一:位运算

异或运算的性质:

  • 任何数和 $0$ 做异或运算,结果仍然是原来的数,即 $x \oplus 0 = x$;
  • 任何数和其自身做异或运算,结果是 $0$,即 $x \oplus x = 0$;

我们对该数组所有元素进行异或运算,结果就是那个只出现一次的数字。

时间复杂度 $O(n)$,空间复杂度 $O(1)$。其中 $n$ 是数组 $nums$ 的长度。

1
2
3
class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(xor, nums)
1
2
3
4
5
6
7
8
9
class Solution {
    public int singleNumber(int[] nums) {
        int ans = 0;
        for (int v : nums) {
            ans ^= v;
        }
        return ans;
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int ans = 0;
        for (int v : nums) {
            ans ^= v;
        }
        return ans;
    }
};
1
2
3
4
5
6
func singleNumber(nums []int) (ans int) {
    for _, v := range nums {
        ans ^= v
    }
    return
}
1
2
3
function singleNumber(nums: number[]): number {
    return nums.reduce((r, v) => r ^ v);
}
1
2
3
4
5
6
7
impl Solution {
    pub fn single_number(nums: Vec<i32>) -> i32 {
        nums.into_iter()
            .reduce(|r, v| r ^ v)
            .unwrap()
    }
}
1
2
3
4
5
6
7
/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function (nums) {
    return nums.reduce((a, b) => a ^ b);
};
1
2
3
4
5
public class Solution {
    public int SingleNumber(int[] nums) {
        return nums.Aggregate(0, (a, b) => a ^ b);
    }
}
1
2
3
4
5
6
7
int singleNumber(int* nums, int numsSize) {
    int ans = 0;
    for (int i = 0; i < numsSize; i++) {
        ans ^= nums[i];
    }
    return ans;
}
1
2
3
4
5
class Solution {
    func singleNumber(_ nums: [Int]) -> Int {
        return nums.reduce(0, ^)
    }
}

方法二

1
2
3
4
5
class Solution {
    public int singleNumber(int[] nums) {
        return Arrays.stream(nums).reduce(0, (a, b) -> a ^ b);
    }
}

评论