题目:
给定一个?n?个元素有序的(升序)整型数组?nums 和一个目标值?target ?,写一个函数搜索?nums?中的 target,如果目标值存在返回下标,否则返回 -1。
题解 PHP版本
class Solution {
/**
* @param Integer[] $nums
* @param Integer $target
* @return Integer
*/
function search($nums, $target) {
if(count($nums) == 0 ){
return -1;
}
$left = 0;
$right = count($nums) -1;
while($left <= $right){
$mid = floor( ($left+$right)/2);
if($nums[$mid] == $target){
return $mid;
}
if($nums[$mid] > $target){
$right = $mid-1;
}else{
$left = $mid+1;
}
}
return -1;
}
}
GO版本
func search(nums []int, target int) int {
high := len(nums)
low := 0
for low < high {
mid := low + (high-low)/2
if nums[mid] == target {
return mid
} else if nums[mid] > target {
high = mid
} else {
low = mid+1
}
}
return -1
}
|