Sort
MergeSort
public int crossSum(int[] nums, int left, int right, int p) {
if (left == right) return nums[left];
int leftSubsum = Integer.MIN_VALUE;
int currSum = 0;
for(int i = p; i > left - 1; --i) {
currSum += nums[i];
leftSubsum = Math.max(leftSubsum, currSum);
}
int rightSubsum = Integer.MIN_VALUE;
currSum = 0;
for(int i = p + 1; i < right + 1; ++i) {
currSum += nums[i];
rightSubsum = Math.max(rightSubsum, currSum);
}
return leftSubsum + rightSubsum;
}
public int helper(int[] nums, int left, int right) {
if (left == right) return nums[left];
int p = (left + right) / 2;
int leftSum = helper(nums, left, p);
int rightSum = helper(nums, p + 1, right);
int crossSum = crossSum(nums, left, right, p);
return Math.max(Math.max(leftSum, rightSum), crossSum);
}
public int maxSubArray(int[] nums) {
return helper(nums, 0, nums.length - 1);
}QuickSort
CountingSort
BucketSort
HeapSort
Count the appearance of each word by using a map. Use Priority Queue to rank by frequency of appearance and alphabetic. Pop the top k elements.
T: O(n * logk) where n is the length of array, add n words to heap, each takes logk time. S: O(n)
Follow up:
1) Input is a stream? TreeMap or Use Redis Sorted sets to store, keep good speed as well as store lots of steam data
2) Can't fit memory? Partially read data and count the frequency, cumulate on the map. Use MapReduce to split the data set into different machines and consolidate the results.
1. Sort or Priority Queue: T: O(n*logn) S: O(n)
2. Quick Selection: T: O(n) S: O(n)
280. Wiggle Sort
164. Maximum Gap
Sort the numbers by using comparator:
Then construct.
"Unlike a traditional sorting algorithm, which attempts to sort with the fewest comparisons possible, the goal is to sort the sequence in as few reversals as possible."
Start from current size equal to n and reduce current size by one while it’s greater than 1. Let the current size be n. Do following for every n:
Find index of the maximum element in arr[0..n-1] . Let the index be
'index'Call
flip(arr, index)Call
flip(arr, n-1)
Mergesort. For each number store the index and its value. When merge, count the number of the right is smaller than left, and append the count to the result.
Given an array arr of size n. Find the number of triples (i, j, k) where:
i < j < k
arr[i] < arr[j] < arr[k]

Follow-up: Count number of increasing subsequences in the array
arrof sizek.

Solution 1: dp O(k*n^2)
Solution 2: Merge Sort
Sort all worker-bike distances in a PQ.
Bucket sort, allocate to buckets and compare with values decreasingly.
Last updated
Was this helpful?