LeetCode ❀ 136. Numbers that only appear once/python lambda, reduce() function

topic:

Given a non-empty array of integers, each element appears twice except for one element which appears only once. Find the element that appears only once.

illustrate:

Your algorithm should have linear time complexity. Can you do it without using extra space?

Example 1:

输入: [2,2,1]
输出: 1

 Example 2:

输入: [4,1,2,1,2]
输出: 4

answer:

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce( lambda x, y : x ^ y, nums )



reduce(function, iterable[, initializer])
        function -- 函数,有两个参数
        iterable -- 可迭代对象
        initializer -- 可选,初始参数
先对集合中的第 1、2 个元素进行操作,得到的结果再与第三个数据用 function 函数运算,最后得到一个结果



lambda x, y, z : x + y / z
        lambda是定义一个匿名函数,当你需要一个函数但你只是用一下又不想费劲去定义,就可以用lambda定义一下匿名函数以供我们使用一次

Guess you like

Origin blog.csdn.net/qq_42395917/article/details/126672606