mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-09 11:34:46 +08:00
添加 0015.三数之和.md Scala版本
This commit is contained in:
@ -616,6 +616,49 @@ public class Solution
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
Scala:
|
||||||
|
```scala
|
||||||
|
object Solution {
|
||||||
|
// 导包
|
||||||
|
import scala.collection.mutable.ListBuffer
|
||||||
|
import scala.util.control.Breaks.{break, breakable}
|
||||||
|
|
||||||
|
def threeSum(nums: Array[Int]): List[List[Int]] = {
|
||||||
|
// 定义结果集,最后需要转换为List
|
||||||
|
val res = ListBuffer[List[Int]]()
|
||||||
|
val nums_tmp = nums.sorted // 对nums进行排序
|
||||||
|
for (i <- nums_tmp.indices) {
|
||||||
|
// 如果要排的第一个数字大于0,直接返回结果
|
||||||
|
if (nums_tmp(i) > 0) {
|
||||||
|
return res.toList
|
||||||
|
}
|
||||||
|
// 如果i大于0并且和前一个数字重复,则跳过本次循环,相当于continue
|
||||||
|
breakable {
|
||||||
|
if (i > 0 && nums_tmp(i) == nums_tmp(i - 1)) {
|
||||||
|
break
|
||||||
|
} else {
|
||||||
|
var left = i + 1
|
||||||
|
var right = nums_tmp.length - 1
|
||||||
|
while (left < right) {
|
||||||
|
var sum = nums_tmp(i) + nums_tmp(left) + nums_tmp(right) // 求三数之和
|
||||||
|
if (sum < 0) left += 1
|
||||||
|
else if (sum > 0) right -= 1
|
||||||
|
else {
|
||||||
|
res += List(nums_tmp(i), nums_tmp(left), nums_tmp(right)) // 如果等于0 添加进结果集
|
||||||
|
// 为了避免重复,对left和right进行移动
|
||||||
|
while (left < right && nums_tmp(left) == nums_tmp(left + 1)) left += 1
|
||||||
|
while (left < right && nums_tmp(right) == nums_tmp(right - 1)) right -= 1
|
||||||
|
left += 1
|
||||||
|
right -= 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 最终返回需要转换为List,return关键字可以省略
|
||||||
|
res.toList
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
-----------------------
|
-----------------------
|
||||||
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
<div align="center"><img src=https://code-thinking.cdn.bcebos.com/pics/01二维码一.jpg width=500> </img></div>
|
||||||
|
Reference in New Issue
Block a user