力扣简35 搜索插入位置

很容易实现 最开始在不存在的元素找插入位置时饶了小小一点弯路 最开始想要每次mid改变都记录下来 改出来一点错误

class Solution {

public int searchInsert(int[] nums, int target) {
int loc=0;
int low=0,high=nums.length-1,mid;
while(low<=high) { // 这里最开始丢了等于号
mid=(high+low)/2;
if(nums[mid]==target) {
loc=mid;
break;
}
else if(nums[mid]<target) {
low=mid+1;
}
else if(nums[mid]>target) {
high=mid-1;
}

if(low>high) {
loc=high+1;
}
}
return loc;
}


//public static void main(String[] args) {
//
// Solution solution=new Solution();
// int[] nums= {1,3,5,6};
// int res=solution.searchInsert(nums,16);
//
// System.out.println(res);
// }

}

刷二分查找的题遇到 想法跟当时完全不一样 但是反而更差了哈哈哈哈

 

 

    public static int searchInsert(int[] nums, int target) {
        int head=0,tail=nums.length-1;
        int mid=head+(tail-head)/2;
        while(head<=tail) {
            mid=head+(tail-head)/2;
            if(nums[mid]==target) {
                return mid;
            }
            if(nums[mid]>target) {
                tail=mid-1;
            }
            else if(nums[mid]<target) {
                head=mid+1;
            } 
        }
        return head;
    }

 

posted @ 2021-10-31 13:17  Ssshiny  阅读(31)  评论(1)    收藏  举报