Skip to content

Commit 38874a0

Browse files
authored
Improved task 1
1 parent 907f488 commit 38874a0

File tree

3 files changed

+14
-13
lines changed

3 files changed

+14
-13
lines changed

build.sbt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import Dependencies._
33
lazy val root = (project in file(".")).
44
settings(
55
inThisBuild(List(
6-
scalaVersion := "2.13.8",
6+
scalaVersion := "3.3.1",
77
version := "1.0"
88
)),
99
name := "leetcode-in-scala",

src/main/scala/g0001_0100/s0001_two_sum/Solution.scala

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2,18 +2,19 @@ package g0001_0100.s0001_two_sum
22

33
// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Array #Hash_Table
44
// #Data_Structure_I_Day_2_Array #Level_1_Day_13_Hashmap #Udemy_Arrays #Big_O_Time_O(n)_Space_O(n)
5-
// #2023_10_08_Time_517_ms_(86.66%)_Space_56.2_MB_(68.04%)
5+
// #2024_05_15_Time_680_ms_(76.33%)_Space_59.5_MB_(64.20%)
66

77
object Solution {
88
def twoSum(nums: Array[Int], target: Int): Array[Int] = {
9-
val lookup = scala.collection.mutable.Map[Int, Int]()
10-
for (idx <- nums.indices) {
11-
if (lookup.contains(target - nums(idx))) {
12-
return Array(lookup(target - nums(idx)), idx)
13-
} else {
14-
lookup.addOne(nums(idx) -> idx)
15-
}
9+
val indiced = nums.zipWithIndex
10+
val sortedStruct = indiced.sortBy(_._1)
11+
var i = 0
12+
var j = nums.length - 1
13+
while (i < j && j > 0) {
14+
if sortedStruct(j)._1 + sortedStruct(i)._1 > target then j = j - 1
15+
else if sortedStruct(j)._1 + sortedStruct(i)._1 < target then i = i + 1
16+
else return Array(sortedStruct(i)._2, sortedStruct(j)._2)
1617
}
17-
Array(-1, -1)
18+
return Array(-1, -1)
1819
}
1920
}

src/test/scala/g0101_0200/s0102_binary_tree_level_order_traversal/SolutionSpec.scala

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,15 @@ import org.scalatest.matchers.should.Matchers
77
class SolutionSpec extends AnyFunSuite with Matchers {
88
test("levelOrder") {
99
val root = TreeUtils.constructBinaryTree(List(3, 9, 20, null, null, 15, 7))
10-
Solution.levelOrder(root) shouldBe Array(Array(3), Array(9, 20), Array(15, 7))
10+
Solution.levelOrder(root) shouldBe List(List(3), List(9, 20), List(15, 7))
1111
}
1212

1313
test("levelOrder2") {
1414
val root = TreeUtils.constructBinaryTree(List(1))
15-
Solution.levelOrder(root) shouldBe Array(Array(1))
15+
Solution.levelOrder(root) shouldBe List(List(1))
1616
}
1717

1818
test("levelOrder3") {
19-
Solution.levelOrder(null) shouldBe Array.empty
19+
Solution.levelOrder(null) shouldBe List.empty
2020
}
2121
}

0 commit comments

Comments
 (0)