Search Insert Position

来源:互联网 发布:绝艺 围棋 软件 编辑:程序博客网 时间:2024/06/06 10:00

题目地址:https://leetcode.com/problems/search-insert-position/?tab=Description

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 

从前往后扫描就可以了,找到直接返回下标,找不到或者当前的数字比target大了,也是返回当前下标。

public class SearchInsertPosition {    public int searchInsert(int[] nums, int target) {        if (nums.length == 0)            return 0;        for (int i = 0; i < nums.length; i++) {            if (nums[i] < target)                continue;            else                return i;        }        return nums.length;    }}

这么搞时间复杂度为O(n),有没有更快的方法呢,有,我们注意到原始数组是有序的,那么我们完全可以用二分法查找,这样时间复杂度就成了log2n

0 0
原创粉丝点击