★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-vtpgstzd-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
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.git
You may assume no duplicates in the array.github
Example 1:數組
Input: [1,3,5,6], 5 Output: 2
Example 2:微信
Input: [1,3,5,6], 2 Output: 1
Example 3:code
Input: [1,3,5,6], 7 Output: 4
Example 4:htm
Input: [1,3,5,6], 0 Output: 0
給定一個排序數組和一個目標值,在數組中找到目標值,並返回其索引。若是目標值不存在於數組中,返回它將會被按順序插入的位置。blog
你能夠假設數組中無重複元素。排序
示例 1:索引
輸入: [1,3,5,6], 5 輸出: 2
示例 2:
輸入: [1,3,5,6], 2 輸出: 1
示例 3:
輸入: [1,3,5,6], 7 輸出: 4
示例 4:
輸入: [1,3,5,6], 0 輸出: 0
1 class Solution { 2 func searchInsert(_ nums: [Int], _ target: Int) -> Int { 3 //若是nums爲nil則返回0 4 if nums.isEmpty{return 0} 5 //二分查找也稱折半查找(Binary Search) 6 var low:Int = 0 7 var high:Int = nums.count-1 8 while(low <= high) 9 { 10 var mid = (low+high)/2 11 if nums[mid]==target 12 { 13 return mid 14 } 15 else if nums[mid]<target 16 { 17 low = mid+1 18 } 19 else 20 { 21 high = mid-1 22 } 23 } 24 return low 25 } 26 }