leetcode [35] Search Insert Position / Search Insert Position Elegant violence may be more efficient than binary search

Insert picture description here

Title address

https://leetcode-cn.com/problems/search-insert-position/

Ideas

This question is actually a very simple question, but why is the pass rate relatively low, I understand that everyone has made a mistake in the judgment of the boundary treatment, which is caused.

Here I give a concise way to enumerate violence. The time to solve a violent problem is not necessarily very high. The key depends on the implementation method. It is like the binary search. The time consumption is not necessarily low. It is the same.

The efficiency of my brute force solution is as follows:

Insert picture description here

solution

class Solution {
public:
    int searchInsert(vector<int>& nums, int target) {
        for (int i = 0; i < nums.size(); i++) {
            if (nums[i] >= target) { // 一旦发现大于或者等于target的num[i],那么i就是我们要的结果
                return i;
            }
        }
        return nums.size(); // 如果target是最大的,或者 nums为空,则返回nums的长度
    }
};

I am a code junior. I have been engaged in technical research and development at BAT for many years. I use my spare time to repaint leetcode. For more original articles, please pay attention to "Code Random Notes".

Published 236 original articles · praised 251 · 270,000 views +

Guess you like

Origin blog.csdn.net/youngyangyang04/article/details/105462716