国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

Search Insert Position

2019-11-06 06:20:36
字體:
來源:轉載
供稿:網友

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

我比較笨的就從頭到尾依次的比較,發現這并不是一個很好的辦法,雖然可以完成要求,但是所花費的時間很多。 看到好的方法是用二分查找來解決這個問題。

class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if target < nums[0]: return 0 elif target > nums[-1]: return len(nums) l, r = 0, len(nums) - 1 while l <= r: m = (l + r)/2 if nums[m] == target: return m elif nums[m] > target: if nums[m-1] < target: return m else: r = m -1 elif nums[m] < target: if nums[m+1] > target: return m+1 else: l = m + 1
上一篇:C程序的內存鏡像

下一篇:log4j-usage.html

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 竹北市| 娱乐| 右玉县| 乌兰县| 云浮市| 翁牛特旗| 道孚县| 额尔古纳市| 吴川市| 将乐县| 石城县| 南平市| 兴安盟| 乌恰县| 当雄县| 来宾市| 凤庆县| 遂昌县| 金沙县| 司法| 新乡市| 托里县| 尼木县| 嘉义县| 望江县| 砚山县| 惠东县| 龙州县| 江阴市| 新巴尔虎左旗| 磴口县| 花莲市| 沙洋县| 旌德县| 彰化县| 通榆县| 庆元县| 和静县| 鹤山市| 惠州市| 定州市|