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

原创粉丝点击