SingleNumber python实现

本文介绍了一个整数数组问题,即如何找到数组中仅出现一次的数。通过使用异或操作来实现线性时间复杂度的解决方案,同时避免了额外的空间开销。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Single Number

Given an 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?

题意:一个整数数组中,除了一个数以外的其他数字都出现了两次,求这个只出现了一次的数。

要求:算法必须线性的时间复杂度,并且不需要额外的空间。

思路:主要利用异或的性质。交换性(a^b)^c=a^(b^c),以及a^0=a等

实现:

  

1 class Solution:
2     # @param {integer[]} nums
3     # @return {integer}
4     def singleNumber(self, nums):
5         result = nums[0]
6         for i in range(1, len(nums)):
7             result ^= nums[i]
8         return result
9             

 


           

转载于:https://www.cnblogs.com/JohnnyShy/p/4461330.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值