Time-Space trade-offs (input enhancement, pre-construction)

Source: Internet
Author: User
Introduction:

Consider the following question:

You do not need to use any calculation method. First, calculate the function value (for example, the table that calculates the trigonometric function value) and store the pre-computed values in the computer, when you need this function value

The time complexity is O (1), because you don't need any computation. (This was actually the case before the computer was invented, similar to the trigonometric function lookup table)

Compared with other algorithms that use other algorithms to calculate function values, the time complexity is the best, and it is the fastest. Of course, what price have you paid for the fastest time? Space! Yes, you need a space to store

Store these values, while other algorithms do not need or require much less space.

This is the consideration of Time and Space. Sometimes we need to exchange time for space, and sometimes we need to exchange space for time.

In some algorithm designs, the above simple question has given us some inspiration, in exchange for time !!!

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------

1. Inspired by the above questions, we have a method called enhanced input:Preprocessing of some or all inputs to obtain additional information for storageTo accelerate the resolution of subsequent problems.

Simply put, the input enhancement means that when we get the input, we should not only get the belonging, but also make some processing and investigation on the input to get more information within it, save it as follows:

1) Count sorting

2) Enhanced string matching algorithms: the BM algorithm and KMP algorithm are based on these ideas.

2. Another technology that exchanges space for time isUse extra space for faster and more convenient data accessCalled pre-construction:

1) hash table)

2) B-Tree Index

3. There is also a space-for-time technology: dynamic planning will be discussed as a specialized Algorithm Design Technology in the next chapter.

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------

1. sort by count

The idea is simple:Determine the number of elements that each element has smaller than an array.The actual location of each element is obtained. If there are two elements in array a that are smaller than element x, x should be the third element of A, that is, a [2]. Two loops can get how many elements each element has smaller than it. It is very simple. We store this information in another array, Count, you can calculate the value of Count to its position in:

Easy to implement:


The time complexity is n ^ 2.

Package section7;


/* Chapter 7 space-time weigh input enhancement: Counting sorting */

Public class countingsort {

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub

Int [] num = {, 28 };
Countingsort (Num );
For (INT I = 0; I <num. length; I ++)
System. Out. Print (Num [I] + "");
}

Public static void countingsort (INT [] num ){
// Count sorting: counts the number of elements in each array that are smaller than it. Based on this, determine its position in the ordered array.
Int [] Count = new int [num. Length];
For (INT I = 0; I <count. length; I ++)
Count [I] = 0;

For (INT I = 0; I <num. Length-1; I ++)
For (Int J = I + 1; j <num. length; j ++)
{
If (Num [I] <num [J])
Count [J] ++;
Else
Count [I] ++;
}

Int [] result = new int [count. Length];
For (INT I = 0; I <count. length; I ++)
Result [count [I] = num [I];

For (INT I = 0; I <num. length; I ++)
Num [I] = Result [I];
}
}

-2 2 3 3 8 9 14 15 16 21 24 28 29 65

The time complexity of this algorithm is the same as that of simple sorting. However, when the elements to be sorted in an array meet the following requirements, the time complexity of this algorithm is linear: all elements of array a come from a set of known sizes. For example, all elements in an array are {10, 11, 13, 15, 17}. According to the above idea, you only need to scan the array and count the number of times each element appears to sort array A in order. This method is calledDistribution count.

Certificate ------------------------------------------------------------------------------------------------------------------------------------------------

2. Enhanced input count in string matching

1) KMP

The previously written KMP algorithm is actually an input-enhanced counting algorithm that uses the next [] array to store the local information of the mode string. See the previous article

2) horspool Algorithm

In fact, almost, what KMP, horspool, B-M, are in the Improvement matching failure after moving distance, this improvement is based on some features of the pattern string (such as the next array in KMP ).

These moves are troublesome. I wrote a horspool and posted it directly. I want to know more about it and read the book directly:

Note: I still write according to this idea (How much to move when the matching fails), but do not store the number of arrays to move, but calculate each time.

Package section7;


/* Chapter 2 space-time weigh horspool algorithm */

Public class horspool {

/**
* @ Param ARGs
*/
Public static void main (string [] ARGs ){
// Todo auto-generated method stub

Int Index = horspoolmatching ("gacd", "dfgacfdgacdefdcd ");
System. Out. println (INDEX );

}

Public static int horspoolmatching (string P, string s ){
// The Position of the return mode string in S. If-1 is not returned
Int M = P. Length (); // The length of the pattern string
Int n = S. Length (); // match the length of a string

Int last = m-1; // use last to record the position in the matching string
While (last <n-1)
{
If (P. Equals (S. substring (last + 1-M, last + 1 )))
Return last-(m-1 );
Else
Last = last + move (S. charat (last), P );
}

Return-1;
}

Private Static int move (char C, string p ){
// If the matching between the S string and the mode string fails (at this time, the last character of the S string and the mode string is C), the return distance should be moved.
Int M = P. Length ();
For (INT I = m-2; I> = 0; I --)
If (P. charat (I) = C)
Return (m-1-I );

Return m;
}
}

Running result:

7

Certificate ---------------------------------------------------------------------------------------------------------------------------------------------------

3, B tree

I) concepts and structures

It is also a difficult structure. Used for indexing:

Note that the level-n B tree refers to a node with at most N children (I .e., each node has at most n-1 elements)

1) if it is a level-4 B tree (for example,), each node can have up to three elements (in this example, the root node can also have three elements ), each node has a maximum of four Subtrees.

The first one can also be said from the perspective of the number of elements in the root: its root contains 1 M-1 (equivalent to: its root has 2 to m children)

2) nodes except the root and leaves must have at least m/2 to take the entire element (this is required)

3) perfect balance. (Think about how to insert and delete drops to perfectly balance all leaves on the same layer)

Ii) operations on the B tree:

1) Query

Similar to the Binary Search Tree, the time complexity log (n ). Query is not very difficult, but it is difficult to insert and delete

2) Insert

Insertion may cause the number of elements on a node to be full and split.

3) Delete

More complex, see Introduction to Algorithms

The time complexity of insertion and deletion is also log (n ). The B-tree is very complicated. Let's take a good look at it in the introduction to algorithms. The introduction to algorithms has spent a chapter devoted to B-tree. This book is still too simple, first, let's take a look at the structure of the B-tree, and probably know how the query, insert, and delete operations of the B-tree are dripped. Their complexity is log (n)

Certificate --------------------------------------------------------------------------------------------------------------------------------------------------

Summary:

Let's write so much about it first. The content in this chapter is scattered, mainly to know:

Input enhancement technology (counting sorting, enhanced string matching, etc)

Pre-constructor (B tree, hash table), B tree is very complicated. First, let's take a look at its structure and have a good opportunity to see the Introduction to algorithms.

The hash table is very important. It will be placed in the next 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.