mirror of
https://github.com/halfrost/LeetCode-Go.git
synced 2025-07-05 00:25:22 +08:00
增加 problem 35
This commit is contained in:
@ -0,0 +1,17 @@
|
||||
package leetcode
|
||||
|
||||
func searchInsert(nums []int, target int) int {
|
||||
low, high := 0, len(nums)-1
|
||||
for low <= high {
|
||||
mid := low + (high-low)>>1
|
||||
if nums[mid] >= target {
|
||||
high = mid - 1
|
||||
} else {
|
||||
if (mid == len(nums)-1) || (nums[mid+1] >= target) {
|
||||
return mid + 1
|
||||
}
|
||||
low = mid + 1
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
@ -0,0 +1,58 @@
|
||||
package leetcode
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type question35 struct {
|
||||
para35
|
||||
ans35
|
||||
}
|
||||
|
||||
// para 是参数
|
||||
// one 代表第一个参数
|
||||
type para35 struct {
|
||||
nums []int
|
||||
target int
|
||||
}
|
||||
|
||||
// ans 是答案
|
||||
// one 代表第一个答案
|
||||
type ans35 struct {
|
||||
one int
|
||||
}
|
||||
|
||||
func Test_Problem35(t *testing.T) {
|
||||
|
||||
qs := []question35{
|
||||
|
||||
question35{
|
||||
para35{[]int{1, 3, 5, 6}, 5},
|
||||
ans35{2},
|
||||
},
|
||||
|
||||
question35{
|
||||
para35{[]int{1, 3, 5, 6}, 2},
|
||||
ans35{1},
|
||||
},
|
||||
|
||||
question35{
|
||||
para35{[]int{1, 3, 5, 6}, 7},
|
||||
ans35{4},
|
||||
},
|
||||
|
||||
question35{
|
||||
para35{[]int{1, 3, 5, 6}, 0},
|
||||
ans35{0},
|
||||
},
|
||||
}
|
||||
|
||||
fmt.Printf("------------------------Leetcode Problem 35------------------------\n")
|
||||
|
||||
for _, q := range qs {
|
||||
_, p := q.ans35, q.para35
|
||||
fmt.Printf("【input】:%v 【output】:%v\n", p, searchInsert(p.nums, p.target))
|
||||
}
|
||||
fmt.Printf("\n\n\n")
|
||||
}
|
40
Algorithms/0035. Search Insert Position/README.md
Executable file
40
Algorithms/0035. Search Insert Position/README.md
Executable file
@ -0,0 +1,40 @@
|
||||
# [35. Search Insert Position](https://leetcode.com/problems/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:**
|
||||
|
||||
Input: [1,3,5,6], 5
|
||||
Output: 2
|
||||
|
||||
**Example 2:**
|
||||
|
||||
Input: [1,3,5,6], 2
|
||||
Output: 1
|
||||
|
||||
**Example 3:**
|
||||
|
||||
Input: [1,3,5,6], 7
|
||||
Output: 4
|
||||
|
||||
**Example 4:**
|
||||
|
||||
Input: [1,3,5,6], 0
|
||||
Output: 0
|
||||
|
||||
|
||||
## 题目大意
|
||||
|
||||
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
|
||||
|
||||
你可以假设数组中无重复元素。
|
||||
|
||||
## 解题思路
|
||||
|
||||
- 给出一个已经从小到大排序后的数组,要求在数组中找到插入 target 元素的位置。
|
||||
- 这一题是经典的二分搜索的变种题,在有序数组中找到最后一个比 target 小的元素。
|
Reference in New Issue
Block a user