Why is the same algorithm, your program has been time-out? You have to know the algorithm contest tips

Why is the same algorithm, your program has been time-out? You have to know the algorithm contest tips

Hello everybody, my name is official Qi Jie (qí guān jié), drip CSDN recorded in the course of learning, time flies, the future can be, come together it ~


  I do not know if you have not often encounter such a troubled, why the same algorithm, your program has been time-out? We are using Dafa violence, why people are able to live all the data, but you can only through the first few examples; the same is the use of dp, why you are so much slower than others, and sometimes the last one test points are timed out!
  Although we are using the same idea, the same algorithm, but if you do not pay attention in the algorithm competition in these small details, it will greatly increase the execution time of your program, or even increase the time complexity of your algorithm program lift an order of magnitude! The following bloggers compiled some very commonly used algorithms game some small details, quickly see if you have not caught!

1. Function evaluation length / size of the determination condition for loop

  Many small partners when writing for () loop, like in the judgment condition, but this method appears to save you wrote a variable length, but it puts your program a lot slower. For example, we program as an example in the following two paragraphs:
the first paragraph:

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

int main(){
    vector<int> demo;
    for (int i = 0; i < 100000; ++i) {
        demo.push_back(i);
    }
    int length = demo.size();
    clock_t startTime = clock();
    for (int i = 0; i < length; ++i) {
        demo[i]++;
    }
    clock_t endTime = clock();
    cout<<"执行用时: "<<(endTime - startTime)<<endl;
    return 0;
}
#include <iostream>
#include <ctime>
#include <vector>
using namespace std;

int main(){
    vector<int> demo;
    for (int i = 0; i < 100000; ++i) {
        demo.push_back(i);
    }
    clock_t startTime = clock();
    for (int i = 0; i < demo.size(); ++i) {
        demo[i]++;
    }
    clock_t endTime = clock();
    cout<<"执行用时: "<<(endTime - startTime)<<endl;
    return 0;
}

  It runs inside the first block output is the 执行用时: 401output of the second stage of the program is running 执行用时: 278, you look at these two procedures, although the first block to write a line, using a variable length, but the program was first paragraph more efficient than the second stage of the program is much higher ( 这里提高了30%+的效率),Sometimes not to say that the program is short, the efficiency is high

2. The multi-use complex formulas, assigned to the variable

  This situation is very common, and in many cases we may be a complex calculation we need multiple judgments, assignments and other operations, this timeNever reluctant to declare a new variable to assign it with variables instead of repeating the calculation. For example the following code:

if(min(max_right[i],max_left[i]) - height[i] > 0)
	ans = ans + min(max_right[i],max_left[i]) - height[i];

We can be optimized as follows:

int temp = min(max_right[i],max_left[i]) - height[i];
ans += temp > 0 ? temp : 0;

Block mean the same, but the execution efficiency have to think a lot higher, especially in multiple use.

3. The parity judgment when using the '&' more efficient

  In determining whether an odd or even number of a number, a lot of small partners will use %to find a number is divided by 2 is to be judged, in fact, here we have a more efficient way, that is &with the operation, if a&1 == 1it is a is odd, a&1 == 0then a is an even number.

4. can be converted to a function of iteration, try not to write recursive

  A lot of little friends used to write recursive functions, recursive functions is indeed better idea, write a good program out, but the complexity of the recursive function is very large time complexity and space, very easy out, if we have the time and have the ability to it converted to iteration, we still use iterations would be better, it will save a lot of time and space.

5. learn to use the time for space

  Competition in the algorithm, we generally will often exceed the time limit, but beyond the limitations of space or very little, to the general game is even 16MB 256MB, simply used up ah, but also to open several arrays are fully accounted for not a few bytes, but this program allows us to save time on a hundred times. Take a title here yesterday to write it for example: LeetCode a daily question 42. rainwater , text and code specific topics, in order to facilitate this, we have two pieces of code were to take over.
First piece of code, full of violence:

class Solution {
public:
    int trap(vector<int>& height) {
        int ans = 0;
        int length = height.size();
        int max_left,max_right;
        for(int i = 0; i< length; i++){
            max_left = max_right = 0;
            //找到左面的最高值
            for(int j = i; j >= 0; j--){
                if(height[j] > max_left)
                    max_left = height[j];
            }
            //找到右面的最高值
            for(int j = i; j < length; j++){
                if(height[j] > max_right)
                    max_right = height[j];
            }
            // 当前柱面能够接的雨水为:左右两名最高值的低值,然后减去当前柱面的高度
            ans += min(max_right,max_left) - height[i];
        }
        return ans;
    }
};

The second paragraph, the use of the playing table on the basis of the first paragraph:

class Solution {
public:
    int trap(vector<int>& height) {
        int ans = 0;
        int length = height.size();
        //空vector时直接返回0
        if(length == 0)
            return 0;
        int max_left[length],max_right[length];
        //i = 0时,左面(含当前)最大值为height[0]
        max_left[0] = height[0];
        for(int i = 1; i < length; i++){
            //max_left[i] 赋值为当前柱面的高度和max_left[i-1]最大值
            max_left[i] = max(height[i],max_left[i-1]);
        }
        //i = length -1 时,右面(含当前)最大值为height[length-1]
        max_right[length-1] = height[length-1];
        for(int i = length-2; i >= 0; i--){
            //max_right[i]赋值为当前柱面的值和max_right[i+1]的最大值
            max_right[i] = max(height[i],max_right[i+1]);
        }
        for(int i = 0; i< length; i++){
            // 当前柱面能够接的雨水为:左右两面最高值的低值,然后减去当前柱面的高度,赋值为temp
            int temp = min(max_right[i],max_left[i]) - height[i];
            // 如果temp>0,则ans进行累加,否则加0
            ans += temp > 0 ? temp : 0;
        }
        return ans;
    }
};

Then here we are again posted about the program execution time at both ends were used, the first stage uses a 416ms:
Here Insert Picture Description
the second paragraph uses the 4ms:
Here Insert Picture Description
  time used by the program is the first stage of the second paragraph of program 104times, second paragraph the program uses even less memory than even the first block of 0.1MB, but we look at the difference between the two programs, the second paragraph of our program is the only program in the first paragraph of each iteration, the current cylinder is about looking the highest value, in the use of an array at the beginning of a recorded program, to avoid double counting later. This is just two small array, it will improve the efficiency of the program this end 104times, there obviously is the use of space for time, the results of the second paragraph of space used by the program instead of smaller, this is so amazing!

6. Do not exceed the maximum algorithm O (n ^ 2)

  In our normal algorithm contest, when you write a specific time complexity O (n Algorithm 2) the time, this problem is basically that you cool enough, or you just want to take the first two examples (here ` say, according to the test point of the game, if you can not think, can eventually write a complete violence, can cheat a bit is a bit '). We Generally, time efficiency to O (the n- 2) are generally high, and has been very sad all the sample, if it is the theme of the finale, then, O (n) algorithm are all the more sad examples, may need to optimize O (lgn) before insurance. So we generally have to pay attention at the time to write us a rough time complexity, do not let your brains to write out the program, the final result only after a few example earlier, I minimize the time complexity provides five commonly used to reduce the time of the tips above, you can reference. In general O (n) algorithm is quite easy to write out, in training when he wrote out all the major solution also see more of God, might give you a new problem-solving ideas.


Well, on this issue here, you have any other tips can also share in the comments section oh ~

Published 171 original articles · won praise 910 · views 90000 +

Guess you like

Origin blog.csdn.net/qq_43422111/article/details/105326623