LeetCode OJ算法题(三十四):Search Insert Position

来源:互联网 发布:文华财经交易模型源码 编辑:程序博客网 时间:2024/05/22 10:34

题目:

iven 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

解法:

这道题也是二分查找,只是加入了插入,其实与那里就是二叉树的元素插入,这里不再赘述

public class No34_SearchInsertPosition {public static void main(String[] args){System.out.println(searchInsert(new int[]{1,2,3,4,5,6,8}, 7));}public static int searchInsert(int[] A, int target) {        int low = 0;        int high = A.length-1;        while(low <= high){        int mid = (high-low)/2 +low;        if(target == A[mid]) return mid;        if(target < A[mid]){        high = mid-1;        continue;        }        if(target > A[mid]){        low = mid+1;        continue;        }        }        return low;    }}



0 0
原创粉丝点击