每天一个小程序(十一)--- Search Insert Position

21 篇文章 0 订阅
14 篇文章 0 订阅

SearchInsertPosition

私は絶対にあなたを攻撃することはできません、約束したのですから

神隐之狼

前言:

最近天气反常啊,天天打瞌睡?,今天晚上一定要早点休息,感觉不能再这么下去了,前段时间真是有点颓废。上周末又去玩了一次密室逃脱,不得不吐槽一下这次这个体验真的不行,感觉更类似于鬼屋了,本末倒置。好像这周末还可以约一次,希望这次的会好一点?


package array;

/**
 * @author BlackSugar
 * @date 2019/4/16
 * 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.
 * <p>
 * You may assume no duplicates in the array.
 * <p>
 * Example 1:
 * <p>
 * Input: [1,3,5,6], 5
 * Output: 2
 * Example 2:
 * <p>
 * Input: [1,3,5,6], 2
 * Output: 1
 * Example 3:
 * <p>
 * Input: [1,3,5,6], 7
 * Output: 4
 * Example 4:
 * <p>
 * Input: [1,3,5,6], 0
 * Output: 0
 */
public class SearchInsertPosition {
    /**
     * 查询插入数字的索引
     * 思路:
     * 1、由于是升序数组,直接进行遍历,直到数组当中的数字对象大于等于目标值,则为目标值索引。O(n)
     * 2、二分法,设置中点为(i + j) / 2,目标值于中点比较,左右夹逼
     *
     * @param nums   数组
     * @param target 目标值
     * @return
     */
    public int searchInsert(int[] nums, int target) {
        if (null == nums || nums.length == 0) {
            return 0;
        }
            /*for (int i = 0; i < nums.length; i++) {
                if (nums[i] >= target) {
                    return i;
                }
            }
            return nums.length;*/

        int i = 0, j = nums.length - 1;
        while (i <= j) {
            int mid = (i + j) / 2;
            if (target > nums[mid]) {
                i = mid + 1;
            } else if (target < nums[mid]) {
                j = mid - 1;
            } else {
                return mid;
            }
        }
        return i;
    }

    public static void main(String[] args) {
        System.out.println(new SearchInsertPosition().searchInsert(new int[]{1, 3, 4, 7}, 4));
    }
}

总结:

这道题不难,因为是升序数组,直接迭代就可以了,还可以用二分法进行优化

1、暴力迭代O(n)
2、二分法O(logn)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值