Skip to content

LeetCode: 35. 搜索插入位置 #80

Open

Description

@resse92

二分查找法

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        return lower_bound(nums.begin(), nums.end(), target) - nums.begin();
    }
    
    template<typename ForwardIterator, typename T>
    ForwardIterator lower_bound (ForwardIterator first,
                                ForwardIterator last,
                                T value) {
        while (first != last) {
            auto mid = next(first, distance(first, last) / 2);
            
            if (value > *mid)
                first = ++mid;
            else
                last = mid;
        }
        return first;
    }
};

Activity

  1. changed the title [-]d[/-] [+]LeetCode: 35. 搜索插入位置[/+] on Jun 4, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions