Chapter 9 algorithm Interview Questions 27 maximum continuous subset, Chapter 9 subset
Chapter 9 algorithm official website-original website
Http://www.jiuzhang.com/problem/27/
Question
For an integer set S, the subset D of S is defined as a continuous subset if and only if the integer in D forms a continuous integer sequence. Evaluate the maximum continuous subset of S, that is, the subset that contains the maximum number of consecutive integers. For example, the maximum continuous subset of {1, 3, 4,100,200, 2} is {1, 2, 3, 4}
Answer
In the following example, the time-space complexity is O (n). The Hash table is used to index all consecutive subsets currently found. For each set, the index {first number: Set} and {last number: Set}, for example: {1: {1, 2, 3}, 3: {1, 2, 3}, 5: {5, 6}, 6: {5, 6 }}. When traversing S, assuming traversing to k, check whether the k-1 is the last number and k + 1 is the first number of sets in the Hash table, if yes, merge k into a large set, delete the previous set, and add a new set. In this way, the complexity of each operation is O (1. Finally, find the largest set output in the Hash table.
Interviewer's perspective
The test site for this question is a Hash table. First, you can answer a simple sorting method. The complexity is O (nlogn). At this time, the interviewer will prompt whether there is a better method, so he wants to think about the O (n) method. Naturally, we need to consider that the S set can only be traversed once. Consider using some O (1) complex data structures to accelerate the operation, think of the Hash table. In this way, you can store the Left and Right boundaries of the existing set in the Hash table.