What clever but useless data structure algorithms have?

Before I also wrote one or two articles related to the algorithm tips

Some commonly used algorithms skills summary

[Algorithm]-bit computing skills loaded to force Guide

Today's article, be regarded as a supplement to, and it will list some common algorithms questions, how to use these skills to solve, by using these methods, we can make some algorithms questions become easier.

1, with n & (n - 1) n the last one eliminated 1

In the binary representation of n, if we perform n

n = n & (n - 1)

N then the left and right side can be eliminated 1, e.g.

n = 1001
n - 1 = 1000
n = n & (n - 1) = (1001) & (1000) = 1000

This formula What use is it?

In fact, there are still a lot of use, but also when doing the question will often encounter, I have listed below a few classics, often test the example.

(1), it is determined whether n is a positive integer power of two

If a number is a power of 2, n means the binary representation, only one bit is 1, the other is 0. I, for example, such as

2^0 = 0.....0001

2^1 = 0.....0010

2^2 = 0....0100

2^3 = 0..01000

.....

So, we just need to determine N in binary notation if there is only a 1 on it. According to the usual practice, we may have to shift n, then n judge binary representation of the number of 1. So practice is as follows

    boolean judege(int n) {
        int count = 0;
        int k = 1;
        while (k != 0) {
            if ((n & k) != 0) {
                count++;
            }
            k = k << 1;
        }
        return count == 1;
    }

However, if n & (n - 1), then, a direct elimination of 1 n, and n is 0 can be determined, as follows:

boolean judege(int n){
     return n & (n - 1) == 0;// 
}

And time complexity of this method I O (1).

(2), the integer n is the number of binary 1

For this problem, we can continue with the implementation of n & (n - 1), Each time you can eliminate a 1, when n is 0, the calculation can be performed a total of how many times, as follows:

    public int NumberOf12(int n) {
        int count = 0;
        int k = 1;
        while (n != 0) {
            count++;
            n = (n - 1) & n;
        }
        return count;

(3), will be converted to an integer n m, how many bits need to be changed?

In fact, this question and (2) is almost the same as that question, we only need to calculate two numbers n and m are the number of bits is not the same on it, then we can be different or let n and m, then the results obtained in the calculation of XOR how many 1 on it. E.g

令 t = n & m

T is then calculated the number of bits in a can, the problem can be converted to that question (2) of the.

2, the application of double pointer

In previous articles, I have talked about a double pointer, here I am talking about, the way to add some examples.

(1) the application, in the list of

For two-pointer, I think it's the most for is in the list here, such as "judge singly linked list if there ring", "how a traverse to find the list middle position node", "single list in the penultimate k nodes", etc. problem. For this problem, we can use the two-pointer, and a lot easier. I by the way these three questions how to solve it with a two-pointer.

For example, the first question

We can set a slower pointer and a quick pointer to traverse the list. Slow moving a pointer to a node, and a pointer to the fast movement of the two nodes, if the ring is not linked list, the pointer to the fast been traversed the table, if the ring, the fast and slow cursor pointer will encounter when traversing the second .

For the second question

It is set as a pointer to the fast and slow pointer. A first mobile node slow, and fast two. When traversing the list, when the fast pointer traversal is complete, slow pointer just reached the midpoint.

For the third issue

Providing two pointers, a pointer to where the mobile nodes k. After two pointer moves at the same speed. When the pointer moves first traversal completed, the second pointer is just the inverse of the k-th node.

Some might say, dual analog time complexity is still the same ah. Yes, space complexity and time complexity is not going to change, but I think the double pointer, easier to understand and less error prone.

(2), applied to iterate

Using the head and tail pointers to traverse an array, is also very useful, especially when doing the question, for example, I give an example:

Topic Description: Given an ordered array of integers and a target, find two numbers in the array and to the target value. You can assume only one answer corresponding to each input, and the same element can not be reused.

示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

In fact, this question is leetcode in two numbers, but I'm here for a little revision. For this question, an approach like this:

Traverse the array from left to right, in the process of traversal, taking an element a, then subtracting the sum so that a, so that B can be obtained, i.e. b = sum - a. Since then the array is ordered, we'll use binary search, query b subscript in the array.

In this process, a binary search time complexity is O (logn), scanning from left to right traversal is O (n), so the time complexity of this method is O (nlogn).

However, we use the double pointer approach, from both sides of the head and tail arrays to do the method of attack of the intermediate words, only time complexity is O (n), and the code will be more compact, where I is given bar code, as follows :

public int[] twoSum1(int[] nums, int target) {
    int[] res = new int[2];
    int start = 0;
    int end = nums.length - 1;
    while(end > start){
        if(nums[start] + nums[end] > target){
            end--;
        }else if(nums[start] + nums[end] < target){
            start ++;
        }else{
            res[0] = start;
            res[1] = end;
            return res;
        }
    }
    return res;

}

This example is relatively simple, but this method of head and tail of the double pointer really a lot of use.

3, a ^ b ^ b = a application

Two identical results after the number of XOR is 0, and the results of any number and 0 is XORed itself, take advantage of this feature, can be resolved with a lot of questions, I met several Road in leetcode, I cite here Some examples.

(1) array, a number appears only once, and the rest appear twice, once to find the emergence of a number

This question many people may be stored with a hash table, each time stored record number of times a number appears, and finally traverse the hash table to see which number only appears once. Time complexity of this method is O (n), the spatial complexity is also O (n) a.

We just said, two of the same number of XOR result is 0, 0, and a number of XOR result itself, so we put this group of integer or a whole different look, for example, this set of data: 1, 2, 3, 4, 5, 1, 2, 3, 4. Of which five occurred once, others have suffered twice and took them all XOR, the result is as follows:

As the exclusive or support commutative and associative, so:

1^2^3^4^5^1^2^3^4 = (1^1)^(2^2)^(3^3)^(4^4)^5= 0^0^0^0^5 = 5。

By this method, the spatial complexity is reduced to O (1), and the time constant of the complex, as appropriate Demi

int find(int[] arr){
    int tmp = arr[0];
    for(int i = 1;i < arr.length; i++){
        tmp = tmp ^ arr[i];
    }
    return tmp;
}

to sum up

Because this time around he is busy studying, and did not find too many examples, those questions above, some articles have also written before, here to those seen in the review of some forgotten, and also taking into account there may be a majority of people have not seen.

So, I hope after reading this article, after experiencing some problems, can be a little more thought, if you use these tips, it certainly can greatly reduce the difficulty of the problem.

If you find this quite content to inspire you, to let more people see this article: wish

1, thumbs up , so that more people can see this content

2, number of public attention " hard to force the code farmers ", mainly to write algorithms, basic computer like the article, which has more than 100 original articles

No public home page
Most of the data structures and algorithms reprint articles by various public No. I believe we can make you gain something

and I share a lot of videos, books, resources, and development tools, I welcome you to the attention of the public number: hard to force the code Agriculture , the first time to read my article.

Guess you like

Origin www.cnblogs.com/kubidemanong/p/11135473.html