dimanche 21 janvier 2018

Why the following snippet speed up the code?

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 checkout a top answer of other people, I found a strange code snippet. When I copy-paste the snippet into my answer, the same above code takes only 4ms, which is faster than almost 99% other solutions. Can any one explain for the speed up? And the snippet is following:

#include <vector>
#include <iostream>
using namespace std;

static vector<int> nums=[](){
    std::ios::sync_with_stdio(false);
    cin.tie(NULL);
    return vector<int>{};
}();

Aucun commentaire:

Enregistrer un commentaire