First of all, generally consider the "almighty" brute force (recursion, backtracking). But because the time complexity is often too high, you need to consider better methods such as divide-and-conquer (by dividing and then merging), and space-changing time (such as using a hash table).
In addition, choosing the right data structure can significantly improve efficiency, such as finding the smallest number of k, using heaps instead of arrays.
Again, if the topic allows sorting, then the sort can be considered. For example, to find and to set the value of the two number, first sort, and then use the front and back two pointers to the middle sweep. And if it's already sorted (as in Young's matrix lookup), think about having two points. But what if the title is not allowed to be sorted? At this point, we can consider a greedy algorithm that does not change the sequence of sequences (such as minimum spanning tree prim, Kruskal, and Shortest path Dijkstra), or dynamic programming (e.g. 01 knapsack problem, every step is decision).
2.1 Finding the smallest number of K: Solution 1, Solution 4
Quick sort uses the Divide and conquer strategy to divide a sequence (list) into two sub-sequences (sub-lists).
The steps are:
- Pick an element from the sequence called "Datum" (pivot),
- Reorder the columns, where all elements are placed in front of the datum in a smaller position than the base value, and all elements are larger than the base value behind the datum (the same number can be on either side). After the partition exits, the datum is in the middle of the sequence. This is called partition (partition) operation.
- recursively (recursive) sorts sub-columns that are smaller than the base value elements and sub-columns that are larger than the base value elements.
Import Random
Import Timeit
def quickSort (Numbers):
if len (numbers) <= 1:
return numbers
Pivot = random.choice (numbers)
for inch if i < pivot]
for inch if i = = Pivot]
for inch if i > Pivot]
return QuickSort (less) + equal + quickSort (greater)
def quickselect (Numbers, K):
Pivot = random.choice (numbers)
for inch if i < pivot]
for inch if i = = Pivot]
for inch if i > Pivot]
if k <= len (less):
return Quickselect (less, k)
Elif k <= Len (less) + len (equal):
return less + equal
Else:
return less + equal + quickselect (greater, K-len (less)-len (equal))
def main ():
K = 3
numbers = [18, 27, 9, 65, 33]
Tmpnumbers = QuickSort (Numbers)
Print Tmpnumbers[:k]
Tmpnumbers = Quickselect (numbers, K)
Print Tmpnumbers
if ' __main__ ':
Main ()