[LeetCode]136. 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

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
题后反思:

  1. 此处使用列表要比使用字典多耗费很多时间,超出了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.
题后反思:

  1. 两个相同的数字进行异或运算最终结果是0,题目中出现重复的数字均出现两次,所以利用异或的特性,最终结果就是保留下来的没有重复的数字。

文中都是我个人的理解,如有错误的地方欢迎下方评论告诉我,我及时更正,大家共同进步

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值