鏈接:https://leetcode-cn.com/problems/binary-search
給定一個 n 個元素有序的(升序)整型數組 nums 和一個目標值 target ,寫一個函數搜索 nums 中的 target,如果目標值存在返回下標,否則返回 -1。
示例 1:
輸入: nums = [-1,0,3,5,9,12], target = 9
輸出: 4
解釋: 9 出現在 nums 中並且下標爲 4
示例 2:
輸入: nums = [-1,0,3,5,9,12], target = 2
輸出: -1
解釋: 2 不存在 nums 中因此返回 -1
提示:
你可以假設 nums 中的所有元素是不重複的。
n 將在 [1, 10000]之間。
nums 的每個元素都將在 [-9999, 9999]之間。
/* 思路:
二分, 注意邊界
*/
int search(int* nums, int numsSize, int target){
int mid = 0;
int start = 0;
int end = numsSize - 1;
while(mid >= start && mid <= end){
if(target > nums[mid]){ start = mid + 1; }
if(target < nums[mid]){ end = mid - 1; }
if(target == nums[mid]){ return mid; }
mid = (end - start) / 2 + start;
}
return -1;
}