LeetCode-Single Number-解題報告

原題鏈接 https://leetcode.com/problems/single-number/

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

找出唯一一個只出現一次的數。

因爲其他數肯定出現兩次 又因爲A^A = 0, 0^B = B;

所以將數組中所有的數全部異或起來就找到了唯一出現的數

class Solution {
public:
	int singleNumber(vector<int>& nums) {
		int res = 0;
		for (auto& it : nums)res ^= it;
		return res;
	}
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章