题目描述
请实现有重复数字的升序数组的二分查找
给定一个 元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1.
package niu;
import java.util.HashMap;
import java.util.Scanner;
public class niuKe009 {
/*请实现有重复数字的升序数组的二分查找
*给定一个元素有序的(升序)整型数组 nums 和一个目标值 target,
*写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1*/
/*
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 如果目标值存在返回下标,否则返回 -1
* @param nums int整型一维数组
* @param target int整型
* @return int整型
*/
public int search1 (int[] nums, int target) {
/*使用hash表*/
// write code here
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=0; i<nums.length; i++){
if(!map.containsKey(nums[i])) {
map.put(nums[i], i);
}
}
int result=0;
result = map.get(target);
return result;
}
public int search2 (int[] nums, int target) {
/*使用二分查找(可以执行,但是会超时2001ms)*/
// write code here
if (nums == null || nums.length == 0)
return -1;
int low = 0;
int high = nums.length-1;
int mid = 0;
int result=0;
while(low<high){
mid = low+(high-low)/2;
if(nums[mid]>target){
high = mid-1;
}else if(nums[mid]<target){
low = mid+1;
}else if(nums[mid]==target){
result = mid;
}
}
while(target == nums[mid]){
mid--;
}
result = mid+1;
return result;
}
public int search3(int[] nums, int target) {
//边界条件判断,向左逼近
if (nums == null || nums.length == 0)
return -1;
int left = 0;
int right = nums.length - 1;
while (left < right) {
int mid = left + (right - left) / 2;
if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid;
}
}
return nums[left] == target ? left : -1;
}
public static void main(String[] args) {
//System.out.println("[");
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String[] ss = s.split(",");
int[] nums = new int[ss.length];
for(int i=0; i< ss.length; i++){
nums[i] = Integer.valueOf(ss[i]);
}
//System.out.println("]");
Scanner sc2 = new Scanner(System.in);
int target = sc2.nextInt();
niuKe009 Search = new niuKe009();
int r1 = Search.search1(nums,target);
int r2 = Search.search2(nums,target);
System.out.println(r1);
System.out.println(r2);
}
}
知识讲解参考:https://www.cnblogs.com/luoxn28/p/5767571.html