Leikou study notes: 997: the square of an ordered array

Topic :
Algorithm :

  • We use the double pointer algorithm to solve the problem
  • The process of writing questions: At the beginning, the criterion I looked for was the first number greater than or equal to 0. Mid_z represents the pointer that increases from zero, and mid_f represents the pointer that decreases from zero. Repeat the loop again, compare the values ​​corresponding to the two pointers in the loop, and select the smaller one to insert into the ans container. But the last submission timed out. Think about it carefully, there are two for loops, and there are many comparisons inside, so the efficiency is not as efficient as entering the square first and then sorting. In the end, I found that I chose the wrong standard. I should go from the two ends to the middle. This saved many comparisons.
  • Algorithm main body : define two pointers, respectively point to the head and tail, compare the sizes in the loop, and insert them into the ans container.
  • Time complexity: O(n), every piece of data will be traversed once
  • Space complexity: O(n), maintaining an ans container

Source code :

class Solution {
public:
    vector<int> sortedSquares(vector<int>& A) {
        int n = A.size();
        vector<int> ans(n);
        int z = INT_MAX;
        int f = INT_MAX;
        int mid_f = 0;
        int mid_z = n - 1;
        int i = n - 1;

        while(mid_f < mid_z + 1){
            z = INT_MAX;
            f = INT_MAX;

            z = A[mid_z] * A[mid_z];
            f = A[mid_f] * A[mid_f];
    
            if(z < f){
                ans[i] = f;
                i--;
                mid_f++;
            }
            else{
                ans[i] = z;
                i--;
                mid_z --;
            }
        }


        return ans;
    }
};

Guess you like

Origin blog.csdn.net/qq_45914759/article/details/109122260