Leetocde35-搜索插入位置

Leetocde35-搜索插入位置_第1张图片

官方题解

class Solution {
    public int searchInsert(int[] nums, int target) {
        int n = nums.length;
        int left = 0, right = n - 1, ans = n;
        while (left <= right) {
            int mid = ((right - left) >> 1) + left;
            if (target <= nums[mid]) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }
}


我的做法

class Solution {
    public int searchInsert(int[] nums, int target) {
        int l=0,h=nums.length-1;
        int mid=(l+h)/2;
        while(l<h){
            mid=(l+h)/2;
            if(target < nums[mid]){
                h=mid-1;
                
            }else if(target > nums[mid]){
                l=mid+1;
            }
            else{
                break;
            } 
        }
        if(target == nums[mid]){
            return mid;
        }
        if(l>=h){

            if (target<=nums[l]){
                return l;
            }
            else if(nums[h]<=target){
                return h+1;
            }
            else if(nums[l-1]<target&&nums[h]>target){
                return h;
            }
            
        }
        return 0;
    }
}

你可能感兴趣的:(LeetCode题库,java,算法,二分查找)