Search Insert Position

来源:互联网 发布:linux 启动脚本 编辑:程序博客网 时间:2024/06/03 02:25

问题描述:一个排好序的int数组,给定一个值target。如果数组中有target,返回target的下标,如果target不再数组里,返回其插入进数组的下标。


解决:对于排好序的数组,使用二分法查找。


/* * 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 */public class SearchInsert {    public int searchInsert(int[] nums, int target) {         if(nums == null || nums.length == 0) {                return -1;        }                int begin = 0;        int end = nums.length-1;        while(begin <= end) {         int mid = (begin + end)/2;                if(target == nums[mid]) {                        return mid;                } else if(target < nums[mid]){                        end = mid-1;                } else {                        begin = mid+1;                }        }        return begin;       }}


原创粉丝点击