/*Given an array of integers, every element appears twice except for one. Find that single one.
Note:
Your algorithm should have a linear runtime complexity. Could you implement it without using extra memory?
*/
object SingleNumber {
def findSingle(arr: Array[Int]):Int = {
arr.toBuffer.filter(n => !((arr.toBuffer-=n) contains n))(0)
} //> findSingle: (arr: Array[Int])Int
//> arr : Array[Int] = Array(2, 2, 3, 3, 4, 4, 5, 5, 7, 7, 8, 8, 9, 9, 1)
val arr = Array(2,2,3,3,4,4,5,5,7,7,8,8,9,9,1)
val m = findSingle(arr) //> m : Int = 1
}
本文提供了一种解决方案来找出数组中仅出现一次的元素,该元素在其他所有元素都出现两次的情况下独树一帜。通过使用Scala编程语言实现了一个函数,该函数能够过滤并找到这个独特的元素,同时满足线性时间复杂度的要求。
1270

被折叠的 条评论
为什么被折叠?



