[TOC]
** 聲明**
該系列文章來自:http://aperiodic.net/phil/scala/s-99/
大部分內(nèi)容和原文相同,加入了部分自己的代碼。
如有侵權(quán),請(qǐng)及時(shí)聯(lián)系本人澜建。本人將立即刪除相關(guān)內(nèi)容署恍。
P01 (*) Find the last element of a list.
要求
找出list中的最后一個(gè)元素
方案
- (1)List自帶的last方法(廢話)
def builtInLast[T](list: List[T]): T =list.last
- (2)將list反轉(zhuǎn)碧查,之后取其head
def lastByReverse[T](list: List[T]): T = list.reverse.head
- (3)遞歸
def lastRecursive[T](list: List[T]): T = list match {
case e :: Nil => e
case _ :: tail => lastRecursive(tail)
case _ => throw new NoSuchElementException
}
P02(*) Find the last but one element of a list
要求
找出list中倒數(shù)第二個(gè)元素
Example:
scala> penultimate(List(1, 1, 2, 3, 5, 8))
res0: Int = 5
方案
- (1) reverse.tail.head
def builtInSolution1[T](list: List[T]): T = {
if (list.isEmpty || list.size <= 1) throw new NoSuchElementException
list.reverse.tail.head
}
- (2) init.last
def builtInSolution2[T](list: List[T]): T = {
if (list.isEmpty || list.size <= 1) throw new NoSuchElementException
list.init.last
}
- (3) 遞歸
def recursiveSolution[T](list: List[T]): T = list match {
case e :: _ :: Nil => e
case _ :: tail => recursiveSolution(tail)
case _ => throw new NoSuchElementException
}
P03(*) Find the Kth element of a list.
要求
獲取list中第n(從零開始)個(gè)元素
方案
- (1) list自帶索引(廢話)
def builtInSolution[T](n: Int, list: List[T]): T = {
if (n < 0) throw new NoSuchElementException
list(n)
}
- (2) 遞歸
def recursiveSolution[T](n: Int, list: List[T]): T = (n, list) match {
case (0, e :: _) => e
case (x, _ :: tail) => recursiveSolution(x - 1, tail)
case (_, Nil) => throw new NoSuchElementException
}
P04 (*) Find the number of elements of a list.
要求
計(jì)算list的長(zhǎng)度
Example:
scala> length(List(1, 1, 2, 3, 5, 8))
res0: Int = 6
方案
- (1) list.length(廢話)
def buildInSolution[T](list: List[T]): Int = list.length
- (2) 普通遞歸
def recursiveSolution[T](list: List[T]): Int = list match {
case Nil => 0
case _ :: tail => 1 + recursiveSolution(tail)
}
- (3) 尾遞歸
def lengthTailRecursive[T](list: List[T]): Int = {
def lengthR(x: Int, list: List[T]): Int = list match {
case Nil => x
case _ :: tail => lengthR(x + 1, tail)
}
return lengthR(0, list)
}
- (4) foldLeft
def builtInSolution2[T](list: List[T]): Int =
list.foldLeft(0)((c, head) => c + 1)
- (5) 遍歷list(沒啥好說的)
P05 (*) Reverse a list.
要求
逆轉(zhuǎn)一個(gè)list
Example:
scala> reverse(List(1, 1, 2, 3, 5, 8))
res0: List[Int] = List(8, 5, 3, 2, 1, 1)
方案
- (1) list.reverse(廢話)
def builtInSolution[T](list: List[T]): List[T] = list.reverse
- (2) 遞歸
def recursiveSolution[T](list: List[T]): List[T] = list match {
case Nil => List()
case h :: tail => recursiveSolution(tail) ::: List(h)
}
- (3) 尾遞歸
def reverseTailRecursive[T](list: List[T]): List[T] = {
def recursiveR(ret: List[T], l: List[T]): List[T] = l match {
case Nil => ret
case h :: tail => recursiveR(h :: ret, tail)
}
return recursiveR(Nil, list)
}
- (4) foldLeft
def reverseFunctional[A](ls: List[A]): List[A] =
ls.foldLeft(List[A]()) { (ret, head) => head :: ret }