《leetcode》search-insert-position
生活随笔
收集整理的這篇文章主要介紹了
《leetcode》search-insert-position
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目描述
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.
Here are few examples.
[1,3,5,6], 5 → 2
[1,3,5,6], 2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6], 0 → 0
解析:該題目一看就像是插入排序的思路。不過我們可以通過觀察測試用例來做。分4種情況討論:
1.target<=最小值;
2.target==最大值;
3.target>最大值;
4.target介于最小值與最大值之間
需要分兩種情況
(1)target==當(dāng)前值,直接返回當(dāng)前值的下標(biāo);
(2)target>當(dāng)前值,小于下一個值,就返回下一個值的下標(biāo)
總結(jié)
以上是生活随笔為你收集整理的《leetcode》search-insert-position的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 《编程题》找出数组中出现次数超过一半的数
- 下一篇: 《leetcode》pascals-tr