Skip to content

Commit 6e97403

Browse files
committed
#35: Search Insert Position; solution & tests.
1 parent 9f7744c commit 6e97403

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/**
2+
* 35
3+
* Search Insert Position
4+
**
5+
* Given a sorted array of distinct integers and a target value,
6+
* return the index if the target is found.
7+
* If not, return the index where it would be if it were inserted in order.
8+
*
9+
* You must write an algorithm with O(log n) runtime complexity.
10+
*
11+
* Example 1:
12+
* Input: nums = [1,3,5,6], target = 5
13+
* Output: 2
14+
*
15+
* Example 2:
16+
* Input: nums = [1,3,5,6], target = 2
17+
* Output: 1
18+
*
19+
* Example 3:
20+
* Input: nums = [1,3,5,6], target = 7
21+
* Output: 4
22+
*
23+
* Constraints:
24+
* • 1 <= nums.length <= 10^4
25+
* • -10^4 <= nums[i] <= 10^4
26+
* • nums contains distinct values sorted in ascending order.
27+
* • -10^4 <= target <= 10^4
28+
**
29+
* https://leetcode.com/problems/search-insert-position/
30+
***/
31+
32+
namespace Problems;
33+
34+
public class SearchInsertPosition
35+
{
36+
public int SearchInsert( int[] nums, int target )
37+
{
38+
int left = 0;
39+
int right = nums.Length - 1;
40+
41+
while ( left <= right )
42+
{
43+
int middle = ( right - left ) / 2 + left;
44+
45+
if ( nums[middle] == target )
46+
{
47+
return middle;
48+
}
49+
else if ( nums[middle] > target )
50+
{
51+
right = middle - 1;
52+
}
53+
else
54+
{
55+
left = middle + 1;
56+
}
57+
}
58+
59+
return left;
60+
}
61+
}
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
using NUnit.Framework;
2+
3+
using Problems;
4+
5+
public class SearchInsertPositionTests
6+
{
7+
[TestCase( new int[] { 1, 3, 5, 6 }, 5, ExpectedResult = 2 )]
8+
[TestCase( new int[] { 1, 3, 5, 6 }, 2, ExpectedResult = 1 )]
9+
[TestCase( new int[] { 1, 3, 5, 6 }, 7, ExpectedResult = 4 )]
10+
[TestCase( new int[] { 1, 3 }, 2, ExpectedResult = 1 )]
11+
public int SearchInsertTest( int[] nums, int target ) =>
12+
new SearchInsertPosition().SearchInsert( nums, target );
13+
}

0 commit comments

Comments
 (0)