这道题是LeetCode里的第35道题。
题目描述:
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
示例 1:
输入: [1,3,5,6], 5 输出: 2
示例 2:
输入: [1,3,5,6], 2 输出: 1
示例 3:
输入: [1,3,5,6], 7 输出: 4
示例 4:
输入: [1,3,5,6], 0 输出: 0
二分查找,简单快捷。每一次将被查找区间分为两块,然后再与该区间的中间值比较,根据比较的结果判断是左边还是右边。
解题代码:
class Solution {
public static int find(int[] nums, int start, int end, int target) {
if (start >= end) {
if (target <= nums[start])
return start;
else
return start + 1;
}
int half = (start + end) / 2;
if (target == nums[half])
return half;
else if (target > nums[half])
return find(nums, half + 1, end, target);
else
return find(nums, start, half - 1, target);
}
public static int searchInsert(int[] nums, int target) {
if (nums.length == 0)
return 0;
// if(nums.length == 1)return find(nums, 0 ,0, target);
int half = (nums.length) / 2;
if (target == nums[half])
return half;
else if (target > nums[half])
return find(nums, half, nums.length - 1, target);
else
return find(nums, 0, half - 1, target);
}
}
提交结果:
个人总结:
这道题算是二分查找的入门题。