zoukankan      html  css  js  c++  java
  • Leetcode: 35. Search Insert Position

    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.

    Example

    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
    

    思路

    • 思路1, 二分查找
    • 思路2,线性
    • 线性跑出来比二分快一倍。这测试用例。。

    代码

    • 二分
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int len = nums.size();
            if(len == 0) return 0;
            
            int low = 0, high = len - 1, mid = 0;
            
            while(low <= high){
                mid = low + (high - low) / 2;
                
                if(nums[mid] == target) return mid;
                else if(nums[mid] > target) high = mid - 1;
                else low = mid + 1;
            }
            
            return low;
        }
    };
    
    • 线性
    class Solution {
    public:
        int searchInsert(vector<int>& nums, int target) {
            int len = nums.size();
            if(len == 0) return 0;
            
            int i = 0;
            for(i = 0; i < len; ++i){
                if(nums[i] >= target)
                    return i;
            }
            return i;
        }
    };
    
  • 相关阅读:
    C语言寒假大作战03
    C语言寒假大作战02
    C语言寒假大作战01
    C语言Ⅰ作业12—学期总结
    C语言Ⅰ博客作业11
    C语言Ⅰ博客作业10
    C语言Ⅰ博客作业09
    C语言Ⅰ博客作业08
    C语言ll作业01
    C语言寒假大作战04
  • 原文地址:https://www.cnblogs.com/lengender-12/p/6838337.html
Copyright © 2011-2022 走看看