ALG: beads at the beginning and end

Source: Internet
Author: User
# Include <stdio. h>
/* Three difficulties:
1) Design a stack structure to meet the following conditions: the time complexity of Min, push, and pop operations is O (1)

3) design a system to deal with word collocation. For example, if Chinese and people can be used together, the Chinese people and China are both effective. Requirements:
1) the number of queries per second may exceed;
2) the word order is 10 W;
3) each word can be combined with up to words

When users enter the Chinese people, they need to return information related to the phrase.
*/

/* 2) a string of beads (m) connected at the beginning and end, with N colors (N "= 10). DesignAlgorithmTo retrieve a segment, which must contain all the colors in N and minimize the length. Analyze the time complexity and space complexity.
Time: O (m)
Space: O (n )*/
# Define max_n 10
Bool select (int m, int const * data, int N, int * start_idx, int * length)
{
Int color [max_n];
Int ncolor = 0;
Memset (color, 0, sizeof (color ));

* Start_idx = 0, * length = m;

Int best_start_idx = 0;
Int best_length = m;

For (INT I = 0; I <m-N; I ++)
{
If (! Color [DATA [I]) ncolor ++;
Color [DATA [I] ++;

If (ncolor = N & i-best_start_idx + 1 <best_length)
{
Best_length = i-best_start_idx + 1;
* Start_idx = best_start_idx;

Color [DATA [best_start_idx] --;
If (0 = color [DATA [I])
Ncolor --;
Else
I --;
Best_start_idx ++;
}
}

Return true;
}

Int main (INT argc, char * argv [])
{
Int n = 6;
Int data [] = {0, 1, 2, 3, 4, 5, 4, 2, 3, 0, 2, 3 };
Int M = sizeof (data)/sizeof (data [0]);

Int start_idx;
Int length;
Select (M, Data, N, & start_idx, & length );

return 0;
}

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.