给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
eg1:[1,3,5,6], 5 输出: 2
eg2:[1,3,5,6], 2 输出: 1
方法一:将要比较的值的位置分为三种情况,分别为:比数组最小值小,比数组最大值大,在数组中
public class Solution {
public static void main(String[] args) {
int[] nums ={1,3,5,6};
int target = 2;
Solution s = new Solution();
System.out.println(s.searchInsert(nums, target));
}
public int searchInsert(int[] nums, int target) {
for(int i=0;i<nums.length;i++){
if(nums[i]==target){
return i;
}
if(nums[nums.length -1]!=target && target>nums[nums.length -1]) return nums.length;
if(nums[nums.length -1]!=target && target<nums[0]) return 0;
if(nums[nums.length -1]!=target && nums[i]<target && nums[i+1]>target) return i+1;
}
return target;
}
}
方法二:二分查找;
class Solution {
public static void main(String[] args) {
int[] nums ={1,3,5,6};
int target = 7;
Solution s = new Solution();
System.out.println(s.searchInsert(nums, target));
}
public int searchInsert(int[] nums, int target) {
if(nums == null || nums.length < 1) return 0;
int low = 0;
int high = nums.length-1;
int mid = 0;
while(low<=high){
mid = low + (high-low)/2;
if(nums[mid] == target){
return mid;
}
if(nums[mid] < target ){
low = mid+1;
}else{
high = mid-1;
}
}
return low;
}
}
本文介绍了一种在已排序数组中查找特定目标值的方法,包括两种主要算法:线性搜索和二分查找。线性搜索通过遍历数组确定目标值的位置或插入点,而二分查找则更高效,适用于大型数据集,通过不断缩小搜索范围直至找到目标或确定插入位置。

被折叠的 条评论
为什么被折叠?



