136. Single Number


做题历程:

  1. 应该不止做了一次了,独立解出,大概耗时4分钟

本题难度并不高,但是第一次做就会有些难,这应该是Bit Manipulation题目的共同特点。本题使用按位异或C++表示为^,如果两个相同,异或后会等于0,唯独没有重复的数,不受影响,所以循环异或后,结果为该数。代码如下:


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

results matching ""

    No results matching ""