35.搜索插入位置Java
题目描述
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。
输入输出样式
示例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
本文题来自LeetCode:https://leetcode-cn.com/problems/search-insert-position/
思路
比较简单,直接使用二分查找,稍作变改。二分查找如果没找到返回-1,此题中没有找到需要返回要插入的位置,稍作思考其实就是把返回low就相当于没有找到的情怀下应该插入的位置。
算法分析
时间复杂度为O(logN),空间复杂度为O(1)
求解函数
public int searchInsert(int[] nums, int target) {
int low = 0, high = nums.length - 1;
while (low <= high){
int mid = (low + high) / 2;
if (nums[mid] == target) return mid;
else if (nums[mid] > target) high = mid - 1;
else low = mid + 1;
}
return low;
}
主函数调用
class Solution35 {
public static void main(String[] args) {
int[] num = {1, 3, 5, 6};
Solution35 sol = new Solution35();
System.out.println(sol.searchInsert(num,2));
}
public int searchInsert(int[] nums, int target) {...}
}