小言_互联网的博客

LeetCode 35:搜索插入位置(Search Insert Position)

375人阅读  评论(0)

题目

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.
Example 1:

Input: [1,3,5,6], 5
Output: 2

思路一

for循环一个一个实验时间复杂度O(n)空间复杂度O(1)

public static int searchInsert(int[] nums,int target){
        if (nums.length<=0){
            return -1;
        }else {
            if (nums[nums.length-1]<target){
                return nums.length;
            }else {
                for (int i = 0; i <nums.length ; i++) {
                    if (nums[i]>=target){
                        return  i;
                    }
                }
            }
        }
        return -1;
    }

思路二

因为数组是个排好序的可以用二分法

public static int searchInsert1(int[] nums,int target){
        int l=0;
        int r = nums.length-1;
        while (l <= r){
            int mid = (r + l);
            if (target > nums[mid]){
                l = mid + 1;
            }
            else{
                r = mid - 1;
            }
        }
        return l;
    }

参考文章
https://leetcode.com/problems/search-insert-position/

Leetcode 35:搜索插入位置


转载:https://blog.csdn.net/linjpg/article/details/104829136
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场