Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions solution/search-insert-position/README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,29 @@
## 35 Search Insert Position

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume no duplicates in the array.

**Example 1:**
```text
Input: [1,3,5,6], 5
Output: 2
```

**Example 2:**
```text
Input: [1,3,5,6], 2
Output: 1
```

**Example 3:**

Input: [1,3,5,6], 7
Output: 4
```

**Example 4:**
```text
Input: [1,3,5,6], 0
Output: 0
```
8 changes: 8 additions & 0 deletions solution/search-insert-position/search_insert_position.go
Original file line number Diff line number Diff line change
@@ -1,2 +1,10 @@
package search_insert_position

func searchInsert(nums []int, target int) int {
for i, v := range nums {
if target <= v {
return i
}
}
return len(nums)
}
44 changes: 44 additions & 0 deletions solution/search-insert-position/search_insert_position_test.go
Original file line number Diff line number Diff line change
@@ -1,2 +1,46 @@
package search_insert_position

import "testing"

type caseType struct {
nums []int
target int
expected int
}

func TestSearchInsert(t *testing.T) {
tests := [...]caseType{
{
nums: []int{2, 7, 11, 15},
target: 5,
expected: 1,
},
{
nums: []int{1, 3, 5, 6},
target: 2,
expected: 1,
},
{
nums: []int{1, 3, 5, 6},
target: 7,
expected: 4,
},
{
nums: []int{1, 3, 5, 6},
target: 7,
expected: 4,
},
{
nums: []int{1, 3, 5, 6},
target: 0,
expected: 0,
},
}

for _, tc := range tests {
output := searchInsert(tc.nums, tc.target)
if output != tc.expected {
t.Fatalf("input: %v, output: %v, expected: %v", tc.nums, output, tc.expected)
}
}
}