I was solving the Search Insert Position problem on LeetCode. The following code takes almost 9ms to run all test cases.
class Solution {
public:
int searchInsert(vector<int>& nums, int target) {
int lo = 0, hi = nums.size() - 1;
while (lo <= hi) {
int mid = lo + (hi - lo) / 2;
if (target < nums[mid]) {
hi = mid - 1;
} else if (target > nums[mid]){
lo = mid + 1;
} else {
return mid;
}
}
return lo;
}
};
When I checked out other people's top answers, I found a strange code snippet. When I copy-paste the snippet into my answer, the same code above takes only 4ms, which is faster than almost 99% of other solutions. Can anyone explain the speed up? The snippet is the following:
#include <vector>
#include <iostream>
using namespace std;
static vector<int> nums=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return vector<int>{};
}();