forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request neetcode-gh#514 from ChrisKheng/main
Add scala and go solution for 56-Merge-Intervals
- Loading branch information
Showing
2 changed files
with
50 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
import "sort" | ||
|
||
func merge(intervals [][]int) [][]int { | ||
const ( | ||
start = 0 | ||
end = 1 | ||
) | ||
|
||
sort.SliceStable(intervals, func(i, j int) bool { | ||
return intervals[i][start] < intervals[j][start] | ||
}) | ||
|
||
res := [][]int{intervals[0]} | ||
for i := 1; i < len(intervals); i++ { | ||
currResLastIndex := len(res) - 1 | ||
currEnd := res[currResLastIndex] | ||
curr := intervals[i] | ||
|
||
if currEnd[end] < curr[start] { | ||
res = append(res, curr) | ||
} else if currEnd[end] < curr[end] { | ||
res[currResLastIndex][end] = curr[end] | ||
} | ||
} | ||
|
||
return res | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
import scala.collection.mutable.ArrayBuffer | ||
|
||
object Solution { | ||
def merge(intervals: Array[Array[Int]]): Array[Array[Int]] = { | ||
val (start, end) = (0, 1) | ||
val sortedIntervals = intervals.sortBy(_(start)) | ||
val res = ArrayBuffer[Array[Int]](sortedIntervals(0)) | ||
|
||
for (i <- 1 until sortedIntervals.length) { | ||
val currEndIdx = res.size - 1 | ||
val currEnd = res(currEndIdx) | ||
val curr = sortedIntervals(i) | ||
|
||
if (currEnd(end) < curr(start)) { | ||
res += curr | ||
} else { | ||
res(currEndIdx)(end) = currEnd(end).max(curr(end)) | ||
} | ||
} | ||
|
||
return res.toArray | ||
} | ||
} |