这几天开始刷lintcode,准备把自己做过的题写出来保存下来。算法小白,写的不好勿喷。
题目是:给定一个排序的整数数组(升序)和一个要查找的整数target
,用O(logn)
的时间查找到target第一次出现的下标(从0开始),如果target不存在于数组中,返回-1
。
class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
//write your code here
int low=0;
int high=nums.length-1;
int mid=0;
int result=-1;
while(low<=high){
mid=(low+high)/2;
if(nums[mid]<target){
low=mid+1;
}else if(nums[mid]>target){
high=mid-1;
}else{
result=mid;
high=mid-1;
}
}
return result;
}
}
同样寻找最后一个元素只需要改变一行代码就行
class Solution {
/**
* @param nums: The integer array.
* @param target: Target to find.
* @return: The first position of target. Position starts from 0.
*/
public int binarySearch(int[] nums, int target) {
//write your code here
int low=0;
int high=nums.length-1;
int mid=0;
int result=-1;
while(low<=high){
mid=(low+high)/2;
if(nums[mid]<target){
low=mid+1;
}else if(nums[mid]>target){
high=mid-1;
}else{
result=mid;
low=mid+1;
}
}
return result;
}
}