leetcode35 搜索插入位置
文章目录
leedcode35 搜索插入位置
解题思路主要为目标数组为有序数组,用二分法查找效率更高
//题目:
//给定一个排序数组和一个目标值,在数组中找到目标值,
并返回其索引。如果目标值不存在于数组中,返回它将会被按
顺序插入的位置。
//
// 你可以假设数组中无重复元素。
public class searchInsertSolution {
public static int searchInsert(int[] nums, int target) {
//如果比第一位还要小或数组长度为0返回0
if (nums[0] > target && nums.length == 0) {
return 0;
}
//二分法
int i = 0, j = nums.length;
while (i < j) {
int med = (i + j) / 2;
if (nums[med] == target) {
return med;
} else if (nums[med] > target) {
j = med - 1;
} else {
i = med + 1;
}
}
return i;
}
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论