Stack
算法解释
冒泡排序
|
|
插入快速排序
|
|
快速排序
快速排序主要思想通过划分将待排序的序列分成前后两部分,其中前一部分的数据都比后一部分的数据要小,然后再递归调用函数对两部分的序列分别进行快速排序,以此使整个序列达到有序。
主要难点在 partition 函数的实现:
- 选择 nums[r] 作为 pivot
- 记录指针 i,表示在 [l, i] 数组元素 <= pivot
- 遍历指针 j,每次加一
- 遍历完毕之后,交换 nums[i] 与 nums[r]
|
|
归并排序
定义 mergeSort(nums, l, r) 函数表示对 nums 数组里 [l,r][l,r] 的部分进行排序,整个函数流程如下:
- 递归调用函数
mergeSort(nums, l, mid)对 nums 数组里[l,mid]部分进行排序。 - 递归调用函数
mergeSort(nums, mid + 1, r)对 nums 数组里[mid+1,r]部分进行排序。 - 此时 nums 数组里
[l,mid]和[mid+1,r]两个区间已经有序,我们对两个有序区间线性归并即可使 nums 数组里[l,r]的部分有序。
|
|
桶排序
|
|
Quick Select
|
|
Three way partition
题解
- 31 Next Permutation
- O(n) time (worst case is reverse) and O(1) space by finding the least significant number a i.e. there is b less significant than b and a < b.
- Simulating the DFS stack and judging at each depth whether the chose one is the maximum in possible number set also works.
- 57 Insert Interval
- O(nlog(n)) time by sorting and merge.
- O(n) time by direct insert.
- 148 Sort List
- O(nlog(n)) time by merge sort. O(1) space by bottom-up sorting.
|
|
- 179 Largest Number
- Given a list of non-negative integers, concatenate them into the largest number.
- O(nlog(n)) time by custom sorting. For any two numbers, compare which should be the first to form a larger number when they form a new number. For example, 30|309 vs. 309|30.
- 274 H-Index
- Given a citation list, find the author’s H-index.
- O(nlog(n)) time by sorting.
- O(n) time by radix sorting. Any citation larger than n can be treated as n.
- 280 Wiggle Sort
- Given a sorted array A, no replica, sort it i.e. A[0] < A[1] > A[2] < A[3] …
- O(n) time by swapping neighbors.
- 296 Best Meeting Point
- Given points in a grid, find the point where sum of manhattan distance from given points to it is minimized.
- Find the median.
- 324 Wiggle Sort II
- Given an array A, might with replica, sort it i.e. A[0] < A[1] > A[2] < A[3] …
- Average O(n) time by quick selection and push >mid to left and < mid to right.
- 370 Range Addition
- Given a range [0, n] and several range updates, give final values of all points.
- O(nlog(n)) time by sorting the ranges and line sweeping.
- O(n) time and O(1) space by changing range bounds and using prefix sum.
- 451 Sort Characters By Frequency
- 493 Reverse Pairs
- Given a number array, find all (i,j) pairs that num[i] > num[j] * 2.
- Instrumented merge sort or BIT or BST(trie) with binary search. 315 and 327 are the same paradigm.
- 539 Minimum Time Difference
- Given timestamps, find minimum difference. Sort and scan.
- 759 Employee Free Time
- Sort and find holes in intervals.
- 912 Sort an Array
- 969 Pancake Sorting
- Sort an array by reversing its prefixes.
- The minimum number question is NP-hard. See Wikipedia
- 973 K Closest Points to Origin
- 1057 Campus Bikes
- Given positions of bikes and persons, match shortest manhattan distances.
- Sort bike-person pairs according to their distances.
参考资料
Linked Mentions
-
No backlinks found.