每日一题1.--------LeetCode35 - 搜索插入位置

package com.LeetCode;

/**
 * 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
 * <p>
 * 你可以假设数组中无重复元素。
 */
public class SearchInsert {
    public static void main(String[] args) {
        int[] arr = {1, 3, 4, 6, 7};
        int target = 9;
        int i = searchInsert(arr, target);
        System.out.println(i);
        /*//采用二分查找法
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int mid = (right + left) / 2;
            if (arr[mid] == target) {
                System.out.println(mid);
            } else if (arr[mid] > target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        //此时left = right,采用三元运算符
        System.out.println(target <= arr[left] ? left : left + 1);*/
    }
    public static int searchInsert(int[] arr,int target){
        //采用二分查找法
        int left = 0;
        int right = arr.length - 1;
        while (left < right) {
            int mid = (right + left) / 2;
            if (arr[mid] == target) {
                return mid;
            } else if (arr[mid] > target) {
                right = mid;
            } else {
                left = mid + 1;
            }
        }
        //此时left = right,采用三元运算符
        return target <= arr[left] ? left : left + 1;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值