Leetcode Week Practice Contest-37 Code Resolution (c + +) __c++

Source: Internet
Author: User
written in front:

Leetcode This site than needless to say it, everyone in the IT circle should know this site, recently began to look for work, of course, also avoid going to brush the problem, do a more classic programming problems, just see Leetcode have a week, then sign up for participation. To get to the point :

Summary: A total of 4 questions, 1.5 hours of time schedule. The topic is graded to two easy, one medium, one hard. The first question 624. Maximum Distance in Arrays

Topic Description:

Given m arrays, and each array are sorted in ascending order. Now we can pick up two integers from two different arrays (each array picks one) and calculate the distance. We define the distance between two integers a and b to be their, absolute difference. Your task is to find the maximum distance.


This problem starts with a bit of a card, the order is to find the largest value in the same array, and the minimum value in the same array, so that the value of two subtraction is the largest, the given array is already sorted, and the only constraint is that the maximum value and the minimum value can not be selected in the same array .

This problem is a little bit of a classic problem of thinking, called the maximum increment subsequence, which is done using a dynamic programming approach, first, select the first one-dimensional array, build the maximum and minimum values at both ends, and then begin the traversal from the next one-dimensional array, traversing to each one-dimensional array, We assume that one of these values is to be selected in the array, so there are two ways to select the maximum value of the array-the minimum value that was previously maintained, or the maximum value that was previously maintained-the minimum value of the array, with an external variable to maintain the maximum result of the difference, and before traversing the next one-dimensional array, The maximum value and the minimum value of the one-dimensional array are taken to update the maximum and minimum values that have been maintained for a long time;

The code is as follows:

TLE Solution class Solution {public:int maxdistance (vector<vector<int>>& arrays) {int Len
        s = arrays.size ();
        int ret = 0; for (int i=0;i<lens;i++) {for (int j=0;j<lens;j++) {if (I!= j) {ret =
                Max (ret, Arrays[i].back ()-arrays[j].front ());
    }} return ret;

}
};
        Class Solution {Public:int maxdistance (vector<vector<int>>& arrays) {//Maintain maximum distance difference with an external variable
        int ret = 0;
        int min_val = Arrays[0].front (), max_val = Arrays[0].back (); for (int i=1;i< (int) arrays.size (); i++) {//each calculation selects the maximum value of the current array, the minimum value to calculate the difference, and holds the maximum value ret = max (arrays[
            I].back ()-min_val, ret);
            ret = max (Max_val-arrays[i].front (), ret);
            Updates the maximum and minimum values of all array maintenance before the current array min_val = min (Min_val, Arrays[i].front ());
        Max_val = Max (Max_val, Arrays[i].back ());
      }  return ret;
 }
};
The second question 623. ADD One Row to tree

Topic Description: Given The root of a binary tree, then value V and depth D, you need to add a row of nodes with value v. at the Given Depth d. The root node is at depth 1.

The adding rule is:given a positive integer depth d, for each NOT null tree nodes N in depth d-1, create two tree nodes W ith value V as N ' s left subtree root and right subtree root. and N ' s original left subtree should is the left subtree of the the new left subtree root, its original right subtree should b E The right subtree to the new right subtree root. If depth D is 1 This means there is no depth d-1 in all, then create a tree node with value V as the new root of the whole Original tree, and the original are the new root ' s left subtree.


a very simple question, the tree structure, is it, the first choice is to return to do, understand the meaning of the topic after two situations;

One is to insert a row of nodes directly in the root node; the other is to insert a row of nodes in the tree; The choice is to Dfs to do it, after inserting the node and then withdrawing;

/** * Definition for a binary tree node.
 * struct TreeNode {* int val;
 * TreeNode *left;
 * TreeNode *right;
 * TreeNode (int x): Val (x), left (null), right (NULL) {} *};
        * * Class Solution {private:void dfs (treenode* root, int v, int d, int cur) {//Judge edge condition, match remember return, do not conform to continue Dfs
        if (root = = NULL) return;
            if (cur = = d) {treenode* new_left = new TreeNode (v); new_left->left = root->left; treenode* new_right = new TreeNode (v);
            New_right->right = root->right; Root->left = New_left;
            Root->right = New_right;
        Return
        DFS (Root->left, V, D, cur+1);
    DFS (Root->right, V, D, cur+1);
        Public://recursive resolution of the depth priority of the tree treenode* addonerow (treenode* root, int v, int d) {int real = d-1;
            If real is the root node, it is used directly as the root node, and the left node is the original tree if (real = = 0) {treenode* ret = new TreeNode (v);
            Ret->left = root; return reT
            else{treenode* ret = root;
            DFS (Root, V, real, 1);
        return ret; }
    }
};

question number three 625. Minimum factorization

Topic Description:

Given a positive integer A, find the smallest positive integer b whose multiplication of all digit equals to a.

If There is no answer or the answer isn't fit into 32-bit signed integer, then return 0.


as a medium difficult problem, in fact, as long as the rules of the medium, and even hard the problem of the pit will be relatively few;

This problem requires a given number A, a number B, yes, after multiplying each digit B to get A;

From This we can tell that if you want to multiply any number of times and get the number itself, that is related to its own divisors, in this question, consider the number of units multiplied, so you need to exclude the number of irreducible units in the divisor, that is, you can break a number of decomposition, and these decomposition can not exceed 10 , so we can use a data structure to maintain the decomposition of the mass factor, then because the final combination of B is minimal and within the unsigned int representation range, decomposition 2 and 3 can be combined into a larger number (no more than 10), which makes B's range more convergent;

There is a rule for combining decomposition here, starting with as many as 3 2 to form a 8, the remaining 2 and 3 rows in a row, if the total number is odd, take the first place in B's first, and then the remaining 22 combination; If the direct total is even, then the direct 22 combination; This can make the final constituent b smallest;

The code is as follows:

Class Solution {private://using a map to maintain map<int, int> table;
        BOOL Initnums (int a) {int tmp = a, divisor = 2;
            while (TMP!= 1) {if (divisor >=) return false;
                if (Tmp%divisor = = 0) {table[divisor]++;
            TMP/= divisor;
            } else{divisor++;
    } return true; }//Three 2 combined into 8, the remaining 2 and 3 composition sequences, if the cardinality, the first number is retained//sequence of the remaining number 22 multiplied to form a new number into the map//combination map inside the number, if it is an int range of output, otherwise output 0 int deal (MA
        P<int, int>& table) {int tmp = table[2]/3, rest = table[2]% 3;
        TABLE[8] + = tmp;
        Vector<int> Nums (rest, 2), Nums_tmp (table[3), 3); Table.erase (2); 
        Table.erase (3);
        Nums.insert (Nums.end (), Nums_tmp.begin (), Nums_tmp.end ());
        int lens = Nums.size (), i = 0;
            if (Lens > 0) {if (lens&0x01) {i = 1; table[nums[0]] = 1; for (; i<lens;i+=2) {int res = nums[i]*nums[i+1];
            table[res]++;
        Long long res = 0; for (auto K=table.begin (), K!=table.end (); k++) {for (int i=1;i<=k->second;i++) {res = res*1
            0 + k->first;
        } if (Res>=int_min&&res<=int_max) return (INT) res;
    else return 0;
        Public:///////First number is represented as int smallestfactorization (int a) {if (a = = 1) return 1;
        To determine whether the number of prime numbers within 10 can be expressed, can not be returned false if (!initnums (a)) return 0;
    Return deal (table); }
};

question Fourth 621. Task Scheduler

Topic Description:

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent tasks. Tasks could be done without original order. Each task could is done in one interval. For each interval, the CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n-means between two same tasks, there must be at least n intervals The CPU are doing different tasks or just be idle.

You are need to return the least number of intervals the CPU would take to finish all the given tasks.


simulation of the CPU job scheduling mechanism, there are two constraints, one is to make the total consumption of CPU unit time is the smallest, two are each job has a time interval n;

need to ensure that each job at least is more than equal to N per unit time after scheduling again, if not a job needs scheduling, with idle to fill the output;

thinking: First of all, considering to make CPU operating time shortest, that is, to ensure that idle time is the least, then the strategy is to use every priority in the interval between the scheduling of those who need to perform more than a few jobs, at the same time, every cycle n after the need to schedule the number of In order to facilitate the next time also in accordance with the most required number of job priority scheduling strategy to do; so the most intuitive idea is to use the priority queue to complete, while using a secondary queue to assist;

Class Solution {Public:int Leastinterval (vector<char>& tasks, int n) {//first counts the number of occurrences of each word map&
        Lt;int, int> table;
        for (int i=0;i< (int) tasks.size (); i++) table[tasks[i]-' A ']++;
        Priority_queue<int> que;
        for (auto K=table.begin (); K!=table.end (); k++) Que.push (K->second);
        Table.clear ();
        Initialize variable int ret = 0, interval = n+1;
        queue<int> tmp; while (!que.empty ()) {//This case, after the need to calculate through the interval, so it is best to put the interval of the operation into the loop to do//To save the outer layer interval 0break
                And then minus one to 1, affecting subsequent operations while (!que.empty () &&interval) {int val = que.top (); Que.pop ();
                if (val-1 > 0) tmp.push (VAL-1);
            interval--;
            ///Only consider adding a partial number of times if two queues are empty (Tmp.empty () && que.empty ()) ret + n+1-interval;
                Otherwise need to consider idle situation, increase all the Times n+1 else{ret = n+1; While!tmp.empty ()) {int x = Tmp.front (); Tmp.pop ();
                Que.push (x);
        } interval = n+1;
    return ret; }
};

Summary:

Looking for a long way to work, but do not forget beginner's mind, look back to the road.

Code address: [Luuuyi/leetcode-contest]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.