经典二分查找问题
在一个排序数组中找一个数,返回该数出现的任意位置,如果不存在,返回-1
样例
给出数组 [1, 2, 2, 4, 5, 5]
.
- 对于 target =
2
, 返回 1 或者 2. - 对于 target =
5
, 返回 4 或者 5. - 对于 target =
6
, 返回 -1.
public class Solution {
public int findPosition(int[] nums, int target) {
if(nums.length==0||nums==null){
return -1;
}
int start=0;
int n=nums.length;
int end=n-1;
int mid;
while(start+1<end){
mid=(end+start)/2;
if(nums[mid]>=target){
end=mid;
}else{
start=mid;
}
}
if(nums[start]==target){
return start;
}
if(nums[end]==target){
return end;
}
else{
return -1;
}}
}
public int findPosition(int[] nums, int target) {
if(nums.length==0||nums==null){
return -1;
}
int start=0;
int n=nums.length;
int end=n-1;
int mid;
while(start+1<end){
mid=(end+start)/2;
if(nums[mid]>=target){
end=mid;
}else{
start=mid;
}
}
if(nums[start]==target){
return start;
}
if(nums[end]==target){
return end;
}
else{
return -1;
}}
}