leetcode(查找数组中元素位置)
来源:互联网 发布:魔女的条件知乎 编辑:程序博客网 时间:2024/06/05 12:48
题目:
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
思路一:直接遍历
实现代码如下:
package leetcode;public class Solution { public static int searchInsert(int[] A, int target) { int t=0; for(int i=0;i<A.length;i++){ if(A[i]>=target&&target<=A[A.length-1]){ t= i; break; } if(target>A[A.length-1]){ t= A.length; break; } } return t; } public static void main(String[] args) { int[] a={1,3}; int targert=0; System.out.println(searchInsert(a,targert)); }}
思路二:
用二分搜索法来优化我们的时间复杂度
实现代码如下:
public class Solution{ public static int searchInsert(int[] A, int target) { //定义low和high int low=0,high=A.length-1; int mid=0; while(low<=high){ mid=(low+high)/2; if(target>A[mid]){ low=mid+1; }else if(target<A[mid]){ high=mid-1; }else{ return mid; } } // 没找到返回low,即插入位置 return low; } public static void main(String[] args) { int[] a={1,3}; int targert=0; System.out.println(searchInsert(a,targert)); }}
二分查找的主要关键点在于while循环的结束条件low<=high以及没有找到时的返回值为当前的low
阅读全文
0 0
- leetcode(查找数组中元素位置)
- java数组中根据元素查找位置
- 查找数组元素位置
- 查找数组元素位置
- 查找循环数组中元素位置(无重复元素)
- 查找顺序数组中元素第一次出现的位置(二分查找)
- js查找数组元素位置
- js查找数组元素位置
- 折半查找确定插入数组中元素的位置
- java数组中根据元素查找位置 索引
- JS能力测评-查找数组元素位置
- 查找某个元素在数组中的位置
- c++在数组中查找元素并返回位置下标,统计某元素出现次数程序
- Java中数组Arrays.binarySearch,快速查找数组内元素位置
- 旋转数组中查找元素
- 数组中查找指定元素
- 在vector中查找元素及其位置
- 利用折半查找,寻找元素在数组中合适恰当的位置
- Java-简单操作Excel
- Zend Studio快捷键
- 不同电脑上的两台linux使用桥接模式实现互通(静态ip地址)
- HTML5基础归纳(2)--常遇到的兼容问题及解决办法
- 【Java面试知识】异常
- leetcode(查找数组中元素位置)
- 关于vue resource post 参数传不过去
- 学习总结:
- 大数据伪分布式环境搭建hadoop+zookeeper+hive+sqoop+hbase
- 剑指offer——26.二叉搜索树与双向链表
- 日期类定义
- 16.Hadoop架构再探讨第1部分
- java无法调用webservice
- 如何使用GridView实现不同数量显示图片不同的大小