Skip to content

Commit

Permalink
Merge pull request #1009 from 0xff-dev/2848
Browse files Browse the repository at this point in the history
Add solution and test-cases for problem 2848
  • Loading branch information
6boris authored Oct 30, 2024
2 parents 5c5ad4d + 7b792ab commit 88f57e1
Show file tree
Hide file tree
Showing 3 changed files with 107 additions and 0 deletions.
29 changes: 29 additions & 0 deletions leetcode/2801-2900/2848.Points-That-Intersect-With-Cars/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# [2848.Points That Intersect With Cars][title]

## Description
You are given a **0-indexed** 2D integer array `nums` representing the coordinates of the cars parking on a number line. For any index `i`, `nums[i] = [starti, endi]` where `starti` is the starting point of the `ith` car and `endi` is the ending point of the `ith` car.

Return the number of integer points on the line that are covered with **any part** of a car.

**Example 1:**

```
Input: nums = [[3,6],[1,5],[4,7]]
Output: 7
Explanation: All the points from 1 to 7 intersect at least one car, therefore the answer would be 7.
```

**Example 2:**

```
Input: nums = [[1,3],[5,8]]
Output: 7
Explanation: Points intersecting at least one car are 1, 2, 3, 5, 6, 7, 8. There are a total of 7 points, therefore the answer would be 7.
```

## 结语

如果你同我一样热爱数据结构、算法、LeetCode,可以关注我 GitHub 上的 LeetCode 题解:[awesome-golang-algorithm][me]

[title]: https://leetcode.com/problems/points-that-intersect-with-cars/
[me]: https://github.com/kylesliu/awesome-golang-algorithm
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package Solution

import "sort"

func Solution(nums [][]int) int {
sort.Slice(nums, func(i, j int) bool {
a, b := nums[i], nums[j]
if a[0] == b[0] {
return a[1] < b[1]
}
return a[0] < b[0]
})

points := 0
var (
left, right int
first = true
)
for _, car := range nums {
if first {
left, right = car[0], car[1]
points += right - left + 1
first = false
continue
}
if car[0] >= right {
points += car[1] - car[0]
if car[0] > right {
points++
}
left, right = car[0], car[1]
continue
}
if car[1] > right {
points += car[1] - right
right = car[1]
}
}
return points
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package Solution

import (
"reflect"
"strconv"
"testing"
)

func TestSolution(t *testing.T) {
// 测试用例
cases := []struct {
name string
inputs [][]int
expect int
}{
{"TestCase1", [][]int{{3, 6}, {1, 5}, {4, 7}}, 7},
{"TestCase2", [][]int{{1, 3}, {5, 8}}, 7},
}

// 开始测试
for i, c := range cases {
t.Run(c.name+" "+strconv.Itoa(i), func(t *testing.T) {
got := Solution(c.inputs)
if !reflect.DeepEqual(got, c.expect) {
t.Fatalf("expected: %v, but got: %v, with inputs: %v",
c.expect, got, c.inputs)
}
})
}
}

// 压力测试
func BenchmarkSolution(b *testing.B) {
}

// 使用案列
func ExampleSolution() {
}

0 comments on commit 88f57e1

Please sign in to comment.