LeetCode 30 days Challenge - Day 1
本系列將對LeetCode新推出的30天算法挑戰進行總結記錄,旨在記錄學習成果、方便未來查閱,同時望爲廣大網友提供幫助。
Single Number
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
Solution
題目要求分析:給定非空數組,找到單獨出現的元素。
-
時間複雜度:O(n)
-
空間複雜度:O(1)
解法:
關鍵利用異或運算符^
,對於異或運算:
- a ^ a == 0
- a ^ 0 == a
- a ^ b ^ c = a ^ c ^ b
結合題目給出除了目標元素外,其餘元素各出現兩次,不難想到遍歷整個數組,逐個將元素進行異或運算,最後剩下的元素即爲目標。
int singleNumber(vector<int>& nums) {
int res = 0;
for (int n : nums) res ^= n;
return res;
}
傳送門:Single Number
2020/4 Karl