美文网首页
LeetCode 35: Search Insert Posit

LeetCode 35: Search Insert Posit

作者: 二进制研究员 | 来源:发表于2018-09-30 09:16 被阅读8次

    标签:数组,简易

    问题描述

    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.

    给定已排序数组和目标值。如果数组中存在目标值,则返回其索引。否则,返回该值应该插入位置的索引。
    假设数组中不存在重复元素。
    示例:
    输入: [1,3,5,6], 5
    输出: 2

    输入: [1,3,5,6], 2
    输出: 1

    输入: [1,3,5,6], 7
    输出: 4

    输入: [1,3,5,6], 0
    输出: 0

    解决方案

    方法一:遍历法

    遍历数组,查找插入位置

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int len = nums.size();
            if(len == 0) return 0; 
            int i = 0;
            while(i < len && nums[i] < target) 
                i++;
            return i;     
        }
    };
    

    算法分析

    • 时间复杂度:Θ(n)。
    • 程序运行时间:8ms

    方法二:二分查找法

    基于二分查找的思想解决该问题。

    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int len = nums.size();
            if(len == 0) return 0;
            
            if(target > nums[len - 1])
                return len;
            
            int low = 0;
            int high = len - 1;
            int mid;
            while (low <= high) {
                mid = (low + high) / 2;
                if(nums[mid] == target)
                    return mid;
                if(nums[mid] < target)
                    low = mid + 1;
                else if (mid >= 1 && nums[mid - 1] < target)
                    return mid;
                else high = mid - 1;
            }
            return 0;
        }
    };
    

    算法分析

    • 时间复杂度Θ(lgn)
    • 运行时间:8ms

    相关文章

      网友评论

          本文标题:LeetCode 35: Search Insert Posit

          本文链接:https://www.haomeiwen.com/subject/mlvioftx.html