35. Search Insert Position
来源:互联网 发布:以撒的结合mac版下载 编辑:程序博客网 时间:2024/06/08 02:50
Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.
You may assume no duplicates in the array.
Here are few examples.[1,3,5,6]
, 5 → 2[1,3,5,6]
, 2 → 1[1,3,5,6]
, 7 → 4[1,3,5,6]
, 0 → 0
给定一个排好序的数组,在其中查找某目标值,存在则返回对应的索引,不存在则返回应该插入到数组中的index。本质是找到第一个大于等于目标值的元素的下标。
方法一:遍历数组,每个元素都和target相比较,大于target则返回元素索引,小于则指针自增1。在遍历完所有元素仍没有满足,则说明target应该放在数组的最后,同时i自增到了nums.length处,故直接返回i。时间复杂度为O(n)。
public class Solution { public int searchInsert(int[] nums, int target) { if(nums.length==0) return 0; int i=0; while(i<nums.length){ if(nums[i]>=target) return i; i++; } return i; }}
方法二:
二分查找。如果判断过程中出现了nums[mid]==target,则直接返回索引mid;如果数组中没有target这个元素,则在while循环后会出现low>high的情况,而此时low正是target所应该放的位置,故返回low。
public class Solution { public int searchInsert(int[] nums, int target) { if(nums.length==0) return 0; int mid; int low=0; int high=nums.length-1; while(low<=high){ mid=(low+high)/2; if(nums[mid]==target){ return mid;} else if(nums[mid]<target){ low=mid+1; }else{ high=mid-1; } } return low; }}
阅读全文
0 0
- 35.Search Insert Position
- 35. Search Insert Position
- 35.Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- 35. Search Insert Position
- Curling 2.0 (深搜)
- Map的几种遍历
- java中list的遍历,交集,并集,差集,去重,contains(),indexof,.lastIndexOf
- 微信网页版弹窗实现
- OpenCV学习之寻找轮廓实现视频流的运动目标检测
- 35. Search Insert Position
- Java异常的深入研究与分析
- Websphere8.5安装与配置
- SQl语句执行顺序
- java支付接口开发
- 条件编译#ifdef
- 2.2.8—单链表—Swap Nodes in Pairs
- HDU 3923 Invoker 普通染色:乘法逆元与扩展欧几里得
- HDU 6059-Kanade's trio(多校训练第三场->01字典树)