[Kotlin] Korean Coding Test - Programmers - Length of overlapping lines
KotlinQuestion
Three segments are placed parallel.
When a parameter is given a two-dimensional array line with the start and end coordinates of the three lines in the form [start, end], [start, end], [start, end], complete the solution function to return the length of the overlapping parts of two or more lines.
When lines are [0, 2], [-3, -1], [-2, 1]], it is shown as follows.
Two or more lines overlap [-2, -1], [0,1], which is 2 in length.
Restrictions
Length of lines = 3
Length of element in line = 2
All segments are at least 1 in length.
The elements of the lines are in the form of [a, b], and a and b are each the end points of the line segment.(-100 ≤ a < b ≤ 100)
Input/Output Example
Input/Output Example #1
- Input: [[0, 1], [2, 5], [3, 9]]
- Output: 2
Input/Output Example #2
- Input: [[-1, 1], [1, 3], [3, 9]]
- Output: 0
Input/Output Example #3
- Input: [[0, 5], [3, 9], [1, 10]]
- Output: 8
Solve
Find the length of the overlap using the points where the line segments pass.
Code
kotlin
class Solution {
fun solution(lines: Array<IntArray>): Int {
// Since the range of points is -100<=a<b<=100, an array with a total of 200+1 (0) points is created.
val count = Array(201) { 0 }
// Displays all points through which the segment passes.
lines.forEach {
// Line segment length is the total number of points that exist from the start point to the end point minus one
// Therefore, the endpoint is excluded from the repeat statement.
for (i in it[0] until it[1]) count[i + 100]++
}
// Number of overlapping points = Length of overlapping lines
return count.count { it >= 2 }
}
}
text
TEST 1 〉 Pass (0.06ms, 60.2MB)
TEST 2 〉 Pass (0.10ms, 60.7MB)
TEST 3 〉 Pass (0.05ms, 61.3MB)
TEST 4 〉 Pass (0.06ms, 61MB)
TEST 5 〉 Pass (0.05ms, 61MB)
TEST 6 〉 Pass (0.05ms, 60.4MB)
TEST 7 〉 Pass (0.05ms, 61.5MB)
TEST 8 〉 Pass (0.08ms, 61.9MB)
TEST 9 〉 Pass (0.05ms, 59.2MB)
TEST 10 〉 Pass (0.07ms, 58.2MB)