找到排序列表中小于给定数字的最大数字

时间:2017-06-11 12:11:22

标签: scala list

假设我需要在排序列表中找到比给定数字y小的最大数字 例如

def findLargest(xs: List[Int], y: Int): Option[Int] = ???

val xs = List(1, 2, 4, 8)
findLargest(xs, 5) // should return Some(4)
findLargest(xs, 1) // None
findLargest(xs, 9) // Some(8)

您将如何实现此功能?

4 个答案:

答案 0 :(得分:3)

def findLargest(xs: List[Int], y: Int): Option[Int] = {
    xs.takeWhile(_ < y).lastOption
}

答案 1 :(得分:2)

你可以定义为

   def findLargest(xs: List[Int], y: Int): Option[Int] = xs.filter(x => x < y).sorted.lastOption

答案 2 :(得分:1)

由于列表已排序:

def findLargest(xs: List[Int], y: Int): Option[Int] = xs.reverse.find(_ < y)

答案 3 :(得分:1)

使用收集

假设列表按升序排序

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106

Phalcon DevTools (3.1.2)

#!/usr/bin/env php
PHP Notice:  Constant COMPATIBLE_VERSION already defined in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 106
PHP Fatal error:  Maximum recursion depth exceeded in /home/jarno/phalcon-devtools/bootstrap/autoload.php on line 115

Scala REPL

def findLargest(xs: List[Int], y: Int): Option[Int] = 
  xs.reverse.collect { case x if x < y => x }.headOption