LeetCode Single Number

所属专题核心算法
核心标签LeetCode
代码 / 阅读C++11 · 2 min
累计阅读实时统计
TL;DR · 核心摘要

Problem Given an array of integers, every element appears twice except for one. Find that single one. Note: Your algorithm should have...

Problem

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?

一个整型数组,除一个元素外,其余的元素都出现两次,要求不用额外内存,线性时间内找到这个元素

Python 实现

Python· 21 行

# 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?
# author li.hzh

class Solution:
    def singleNumber(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        result = 0
        for val in nums:
            result ^= val
        return result


print(Solution().singleNumber([1, 1, 4, 4, 3, 5, 3, 6, 6]))

分析

题目要去不开额外内存,线性时间,显然需要特殊 运算的支持。这里位运算中的异或运算恰好满足 A ^ B ^ A = B 的规律,符合题意。

OneCoder 信奥远征平台 · oi.coderli.com

看完题解,马上用 240 关实战检验掌握度

覆盖 GESP 1~8 级考纲心法、CSP-J 双栏阅读程序、错题动态变式推演与 90/120 分钟全真模考。

立即闯关
开源代码与考纲字典

配套题解代码归档于 yummy-code 仓库,完整知识点索引见 GESP Wiki。

技术交流与考级答疑

欢迎加入 C++ GESP/CSP 群(688906745) 或 Java/Python 群(982860385)。

同专栏相关推荐

OneCoder

OneCoder

始于 2012

持续记录 C++ GESP/CSP 信奥算法、Java 服务端架构与 Python 工程实战。官方唯一域名:coderli.com

读者讨论与留言

共 0 条讨论
邮箱仅用于接收回复通知,不对外展示
还没有读者留言,欢迎写下你的第一条交流笔记。