zoukankan      html  css  js  c++  java
  • [LeetCode] 136. Single Number(只出现一次的数)

    [LeetCode] 136. Single Number(只出现一次的数)

    Description

    Given a non-empty array of integers nums, every elements appears twice except for one. Find that single one.

    给定一个非空整数数组 num,数组内除了一个数外,其余数都出现了两次。找到那个只出现了一次的数。

    Follow up: Could you implement a solution with a linear runtime complexity and without using extra memory?

    进阶:你能在线性时间内,使用常数额外空间解决该问题吗?

    Examples

    Example 1

    Input: nums = [2,2,1]
    Output: 1
    

    Example 2

    Input: nums = [4,1,2,1,2]
    Output: 4
    

    Example 3

    Input: nums = [1]
    Output: 1
    

    Constraints

    • 1 <= nums.length <= 3 * 10^4

    • -3 * 10^4 <= nums[i] <= 3 * 10^4

    • Each element in the array appears twice except for one element which appears only once.

    Solution

    这题的一种解法是统计各数字出现的次数,然后再找出其中只出现了一次的那个数。

    然而注意到题目中所有数,除了待寻找的那个数,其余数都出现了两次,又根据异或运算的性质 (x ext{xor}x = 0),于是可以想到将数组中的所有元素用异或运算运算一遍,运算结果即为所求。具体代码如下。

    class Solution {
        fun singleNumber(nums: IntArray): Int {
            return nums.reduce { acc, i -> acc xor i }
        }
    }
    

    借助于 Kotlin 的 reduce 方法,可以把解答的代码缩减至一行。reduce 方法是数组和集合的扩展方法之一,其接收一个 lambda 表达式。返回对集合中的每个元素应用该 lambda 计算得到的结果。

    对于 Kotlin 用户来说,需要注意的是 lambda 表达式内的 return 是隐性的(采用 lambda 内最后一条语句的计算结果),这里如果显式写出 return 反而得不到预期的结果。

  • 相关阅读:
    Navi.Soft31.WinForm框架(含下载地址)
    Navi.Soft31.阅读导航
    工作流组件示例(全部开源)
    WinForm中播放视频示例(含源码)
    angularjs实现选项卡实例
    angularjs中使用 <input type="file">标签实现一次最多上传5张图片
    angularjs笔记《二》
    input type="number"时,maxlength不起作用怎么解决
    笔记——《正则表达式》
    如何区分slice、splice和split
  • 原文地址:https://www.cnblogs.com/zhongju/p/13776369.html
Copyright © 2011-2022 走看看