Skip to content

Commit 27d3683

Browse files
ccf05017poppohoo
authored andcommitted
ccf05017 - week16(35.Search_Insert_Position) (#77)
Co-authored-by: poppo <[email protected]>
1 parent d57a103 commit 27d3683

File tree

1 file changed

+26
-0
lines changed
  • LeetCode-Problems/35.Search_Insert_Position

1 file changed

+26
-0
lines changed
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# [35. Search Insert Position](https://leetcode.com/problems/search-insert-position)
2+
3+
## Problem Analysis
4+
- Input array is already sorted and has distinct integers.
5+
- So just find LTE condition value, that may be the near position of inserting
6+
- I try to use `lastIndexWhere` to find the last position of the element that is less than the target value.
7+
8+
## Code
9+
10+
```scala
11+
object Solution {
12+
def searchInsert(nums: Array[Int], target: Int): Int = {
13+
val lastMinPosition = nums.lastIndexWhere(_ < target)
14+
15+
if (lastMinPosition == -1) {
16+
throw new RuntimeException("no such element")
17+
}
18+
19+
lastMinPosition + 1
20+
}
21+
}
22+
```
23+
24+
## Code Analysis
25+
- Actually, use binary-search is the best solution of this problem.
26+
- But I misunderstood which problem I was supposed to solve so timeless.

0 commit comments

Comments
 (0)