File tree Expand file tree Collapse file tree 4 files changed +65
-1
lines changed
main/scala/org/sharpsw/leetcode
test/scala/org/sharpsw/leetcode Expand file tree Collapse file tree 4 files changed +65
-1
lines changed Original file line number Diff line number Diff line change @@ -30,8 +30,11 @@ to keep up with the language and learn how to use the Scala test library as well
3030* Word break
3131* Roman to integer
3232* Maximum SubArray
33+ * Partition list
3334
3435## Versions
36+ * 1.0.17.0 (09/19/2018) - Added Partition List exercise.
37+
3538* 1.0.16.0 (07/21/2018) - Added Maximum SubArray exercise - not optimized version.
3639
3740* 1.0.15.0 (07/16/2018) - Added Roman to Integer exercise.
Original file line number Diff line number Diff line change @@ -5,7 +5,7 @@ lazy val root = (project in file(".")).
55 inThisBuild(List (
66 organization := " com.example" ,
77 scalaVersion := " 2.12.6" ,
8- version := " 1.0.16 .0"
8+ version := " 1.0.17 .0"
99 )),
1010 name := " leetcode-scala" ,
1111 libraryDependencies += scalaTest % Test ,
Original file line number Diff line number Diff line change 1+ package org .sharpsw .leetcode
2+
3+ import scala .collection .mutable .ListBuffer
4+
5+ object PartitionList {
6+ def partition (head : ListNode , x : Int ): ListNode = {
7+ val smaller = ListBuffer .empty[Int ]
8+ val higher = ListBuffer .empty[Int ]
9+
10+ var item = head
11+ while (item != null ) {
12+ if (item._x < x) {
13+ smaller += item._x
14+ } else {
15+ higher += item._x
16+ }
17+
18+ item = item.next
19+ }
20+
21+ val finalResult = smaller ++ higher
22+
23+ if (finalResult.nonEmpty) {
24+ val convertedNodes = finalResult.map(item => new ListNode (item))
25+ val headNode = convertedNodes.head
26+ var currentNode = headNode
27+
28+ var index = 1
29+ while (index < convertedNodes.size) {
30+ val node = convertedNodes(index)
31+ currentNode.next = node
32+ index += 1
33+ currentNode = node
34+ }
35+
36+ headNode
37+ } else null
38+ }
39+ }
Original file line number Diff line number Diff line change 1+ package org .sharpsw .leetcode
2+
3+ import org .scalatest .{FlatSpec , Matchers }
4+ import org .sharpsw .leetcode .PartitionList ._
5+
6+ class PartitionListSpec extends FlatSpec with Matchers {
7+ " Test 001" should " OK" in {
8+ val node1 = new ListNode (1 )
9+ val node2 = new ListNode (4 )
10+ val node3 = new ListNode (3 )
11+ val node4 = new ListNode (2 )
12+ val node5 = new ListNode (5 )
13+ val node6 = new ListNode (2 )
14+ node1.next = node2
15+ node2.next = node3
16+ node3.next = node4
17+ node4.next = node5
18+ node5.next = node6
19+ val result = partition(node1, 3 )
20+ ListNodeUtils .mkString(result) shouldEqual " 1-2-2-4-3-5"
21+ }
22+ }
You can’t perform that action at this time.
0 commit comments