Single Number三連

single number I

Given an array of integers, every element appears twice except for one. Find that single one.app

object Solution {
    def singleNumber(nums: Array[Int]): Int = {
        return nums.reduce(_^_);
      }
  }

single number II

Given an array of integers, every element appears three times except for one, which appears exactly once. Find that single one.oop

def singleNumber(nums: Array[Int]): Int = {
    def loop(nums: Array[Int], len: Int, index: Int, a: Int, b: Int): Int = index match {
      case `len` => b
      case _ => loop(nums, len, index + 1, a ^ nums(index) & ~((b ^ nums(index)) & ~a), (b ^ nums(index)) & ~a)
    }
    loop(nums, nums.length , 0, 0, 0)
  }

single number III

Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.scala

def singleNumber(nums: Array[Int]): Array[Int] = {
    def loop(nums: Array[Int], len: Int, idx: Int, res: Int, dec: Int, a: Int, b: Int): Array[Int] = (idx, res) match {
      case (`len`, 0) => Array(a ^ nums(idx), b)
      case (`len`, _) => Array(a, b ^ nums(idx))
      case (_, 0) => loop(nums, len, idx + 1, nums(idx + 1) & dec, dec, a ^ nums(idx), b)
      case _ => loop(nums, len, idx + 1, nums(idx + 1) & dec, dec, a, b ^ nums(idx))
    }

    val diff = nums.reduce(_ ^ _)
    val dec = diff & -diff
    loop(nums, nums.length - 1, 0, nums(0) & dec, dec, 0, 0)
  }
相關文章
相關標籤/搜索