【LeetCode】#35. 搜索插入位置
给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
请必须使用时间复杂度为 O(log n) 的算法。
方法一:数组遍历
public int searchInsert(int[] nums, int target) { for(int i = 0; i < nums.length;i++){ if(nums[i] >= target){ return i; } } return nums.length; }
方法二:二分法
class Solution { public int searchInsert(int[] nums, int target) { int n=nums.length; int low=0; int high=n-1; int mid; while(low<=high){ mid=(low+high)/2; if(target<nums[mid]){ high=mid-1; }else if(target>nums[mid]){ low=mid+1; }else if(target==nums[mid]){ return mid; } } return high+1; } }
知识点:
无
总结:
判断大小的题目不能只用遍历,有时应使用其他算法增加效率。
本文作者:Canyooo
本文链接:https://www.cnblogs.com/canyooo/p/15255693.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步