题目描述
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
python解法
class Solution:
def singleNumber(self, nums: List[int]) -> int:
d = {}
for val in nums:
if val in d:
del d[val]
else :
d[val] = 1
return list(d)[0]
Runtime: 104 ms
Memory Usage: 16.2 MB
题后反思:
- 此处使用列表要比使用字典多耗费很多时间,超出了1s
C语言解法
int singleNumber(int* nums, int numsSize){
int ans = 0;
for(int i = 0;i<numsSize;i++)
{
ans ^= nums[i];
}
return ans;
}
Runtime: 12 ms, faster than 68.73% of C online submissions for Single Number.
Memory Usage: 7.9 MB, less than 100.00% of C online submissions for Single Number.
题后反思:
- 两个相同的数字进行异或运算最终结果是0,题目中出现重复的数字均出现两次,所以利用异或的特性,最终结果就是保留下来的没有重复的数字。
文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步