Analysis of Three tricky Leetcode interview questions

Source: Internet
Author: User
Tags image flip

Analysis of Three tricky Leetcode interview questions

Recently, when I was idle, I click the Leetcode question to do it. I found that some questions are quite interesting and tricky. In the following three questions, each question seems so easy at the beginning! However, after further analysis, they all have some tips. Instead of going through common ideas, they need to run some tips in a targeted manner.

 

I. Image Rotation Problems

 

 

At first glance, image rotation is actually a very common operation in image geometric transformation. In fact, the original Pixel matrix can be rotated at any angle by multiplying the original Pixel matrix by a rotation transformation matrix based on the method in "Linear Algebra. For this, see "3.6 image rotation" in my Book Digital Image Processing Principles and Practices (MATLAB ". Of course, this is a general algorithm that can rotate an image at any angle. However, in this question, "in-place" is highlighted. The following is an explanation provided by Wikipedia:

In computer science, an in-place algorithm is an algorithm which transforms input using a data structure with a small amount of extra storage space. the input is usually overwritten by the output as the algorithm executes.

To put it bluntly, the minimum space occupation is required. So General Practices won't work. Observe a pixel matrix to rotate 90 degrees. It is not difficult to find the rule: The result matrix is actually an image flip of the original matrix along the horizontal axis, and then flip along the main diagonal line. For example

 

11 12 13 14 23 24 25 26 23 19 15 11

15 16 17 18 19 20 21 22 24 20 16 12

19 20 21 22 → 15 16 17 18 → 25 21 17 13

23 24 25 26 11 12 13 14 26 22 18 14
 

The sample code is as follows.

 

class Solution {public:    void swap(int& a, int& b)    {    int tmp;     tmp = b;    b = a;    a = tmp;    }        void rotate(vector
 
   >& matrix) {        if (matrix.empty()) return;int n = matrix.size(), i = 0, tmp;for (; i < n/2; ++i) {for (int j = 0; j < n; ++j)swap(matrix[i][j], matrix[n-1-i][j]) ;}i = 0;for (; i < n; ++i) {for (int j = 0; j < i; ++j)swap(matrix[i][j], matrix[j][i]);}    }};
 

 

Power issues of 2 and 2

This question describes bit operations. Let's take a look at the features of the binary method of the power of 2:

1 2 4 8 16 ....

1 10 100 1000 10000 ....

Have you found the rule? It is easy to see that if a number is the power of 2, its binary number must be the highest bit of 1, and the rest must be 0. So you can
Each time you determine whether the percentile is 1, shift to the right, and calculate the number of 1 to determine whether it is the power of 2. However, we provide a simpler method, which can be achieved with only one line of code: if the original number is reduced by 1, the highest bit will be dropped by one, the other 0 bits are now changed to 1, so we will get 0 for the two numbers and use this property to solve the problem.

The following is the sample code.

 

 

class Solution {public:    bool isPowerOfTwo(int n) {        return (n > 0) && (!(n & (n - 1)));    }};

 

 

Iii. Primary Element issues

This question does not require complexity. Therefore, there are no more than three solutions to this question if it is only for solving the problem. In the simplest way, you may think of traversing every element in the array, then using another Table to record the number of occurrences of each different element, and then finding the expected result from this Table. The time complexity of this method is O (n), but the space complexity is O (n ). Can we design a Linear Time Complexity Algorithm without occupying extra space? Boyer and Moore put forward a very effective Algorithm in this book: Linear Time Majority Vote Algorithm.

 

MJRTY-A Fast Majority Vote Algorithm, with R. s. boyer. in R. s. boyer (ed .), automated Reasoning: Essays in Honor of Woody Bledsoe, Automated Reasoning Series, Kluwer Academic Publishers, Dordrecht, The Netherlands, 1991, pp. 105-117.

 

Another famous algorithm that Boyer and Moore cooperate with is the well-known BM pattern matching algorithm. Although KMP is well known, more pattern matching algorithms used in reality are based on BM Evolution Algorithms.

 

The Vote Algorithm is described as follows:

Sweep down the sequence starting at the pointer position shown above.

When sweeping, maintain a pair consisting of a current candidate and a counter. Initially, the current candidate is unknown and the counter is 0.

When we move the pointer forward over an element e:

If the counter is 0, we set the current candidate to e and we set the counter to 1. if the counter is not 0, we increment or decrement the counter according to whether e is the current candidate.

When we are done, the current candidate is the majority element, if there is a majority.

 

To put it simply, scan a string in order, set the counter to 0 at the beginning, and save a current candidate. When the same element is encountered, the counter is + 1 and different elements are encountered, the counter is-1. If the counter is 0, set current candidate to the element e currently described. According to this rule, after the scan is completed, the result is Majority Element. For example:

Step 1:

A C B C
^
? : 0

 

Step 2:

A C B C
^
A: 1

 

Step 3:

A C B C
^
A: 2

 

Step 4:

A C B C
^
A: 3

 

Step 5:

A C B C
^
A: 2

 

Step 6:

A C B C
^
A: 1

 

Step 7:

A C B C
^
? : 0

 

Step 8:

A C B C
^
B: 1

 

(We omitted the subsequent steps) continue and finally we will get Result C.

Of course, the premise of this algorithm is that Majority Element does exist.

The following is the sample code.

 

class Solution {public:    int majorityElement(vector
  
   & nums) {        int elem = 0;        int count = 0;                   for(int i = 0; i < nums.size(); i++) {                  if(count == 0) {                elem = nums[i];                count = 1;            }            else {                if(elem == nums[i])                    count++;                else                    count--;            }        }        return elem;    }};
  

It can be seen that each of the above three problems uses some small tricks, which deserves our careful consideration. Enjoy :)

Related Article

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.