大家好,我是毛毛。ヾ(´∀ ˋ)ノ
廢話不多說開始今天的解題Day~
Given a non-empty array of integers nums
, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Input: nums = [2,2,1]
Output: 1
Input: nums = [4,1,2,1,2]
Output: 4
Input: nums = [1]
Output: 1
1 <= nums.length <= 3 * 10^4
3 * 10^4 <= nums[i] <= 3 * 10^4
首先先簡單的翻譯一下題目
給一組陣列,要找出其中只出現過一次的數字,其餘的每個數字只會出現兩次。
作法大致上是這樣
key
的值是1
。class Solution:
def singleNumber(self, nums: List[int]) -> int:
dict = {}
for num in nums:
if num not in dict:
dict[num] = 1
else:
dict[num] += 1
for key in dict:
if dict[key] == 1:
return key
int singleNumber(int* nums, int numsSize){
int ans = 0;
for (int index=0 ; index<numsSize ; index++) {
// printf("\nBefore: %p\n", ans);
ans ^= nums[index];
// printf("After: %p\n", ans);
}
return ans;
}
Python
C
大家明天見