Skip to content

Commit cedd0b0

Browse files
authored
Merge pull request #12 from fartem/35_Search_Insert_Position
2023-02-06 update: added "35. Search Insert Position"
2 parents 659e66f + f2b8c53 commit cedd0b0

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@ Profile on LeetCode: [fartem](https://leetcode.com/fartem/).
2121
| 20. Valid Parentheses | [Link](https://leetcode.com/problems/valid-parentheses/) | [Link](./lib/easy/valid_parentheses.dart) |
2222
| 21. Merge Two Sorted Lists | [Link](https://leetcode.com/problems/merge-two-sorted-lists/) | [Link](./lib/easy/merge_two_sorted_lists.dart) |
2323
| 27. Remove Element | [Link](https://leetcode.com/problems/remove-element/) | [Link](./lib/easy/remove_element.dart) |
24+
| 35. Search Insert Position | [Link](https://leetcode.com/problems/search-insert-position/) | [Link](./lib/easy/search_insert_position.dart) |

lib/easy/search_insert_position.dart

+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// https://leetcode.com/problems/search-insert-position/description/
2+
class Solution {
3+
int searchInsert(List<int> nums, int target) {
4+
if (nums[nums.length - 1] < target) {
5+
return nums.length;
6+
}
7+
var l = 0;
8+
var r = nums.length - 1;
9+
while (l < r) {
10+
var m = l + (r - l) ~/ 2;
11+
if (nums[m] < target) {
12+
l = m + 1;
13+
} else {
14+
r = m;
15+
}
16+
}
17+
return l;
18+
}
19+
}
+14
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import 'package:leetcode_dart/easy/search_insert_position.dart';
2+
import 'package:test/test.dart';
3+
4+
void main() {
5+
group(
6+
'Example tests',
7+
() {
8+
final sip = Solution();
9+
test('2', () => expect(2, sip.searchInsert([1, 3, 5, 6], 5)));
10+
test('1', () => expect(1, sip.searchInsert([1, 3, 5, 6], 2)));
11+
test('4', () => expect(4, sip.searchInsert([1, 3, 5, 6], 7)));
12+
},
13+
);
14+
}

0 commit comments

Comments
 (0)