Leetcode solution to a problem - sorting algorithm Ideas

quick selection

quick selection

For solving Kth Element problem, the problem is the first K elements.

You can use the fast sort of partition () for implementation. Need to disrupt the array, or in the worst case time complexity of O (N 2 ).

stack

For solving TopK Elements problem, the problem is the K smallest elements. Can maintain a minimum heap size K, the smallest element is the smallest element of the heap. The minimum heap heap is required to achieve the big top, big top heap element represents the top of the heap is the largest element of the heap. This is because we want to get k smallest elements, so when traversing to a new element, it is necessary to know whether this new element is smaller than the largest element of the heap, then put a smaller heap largest element was removed, and the new element is added to the heap. So we need to get the maximum element and it is easy to remove the largest element, big top pile can well meet this requirement.

Stack may also be used to solve the problem Kth Element, is obtained k-th largest element size k is after the minimum heap, because the heap using large top to achieve, so the top of the stack elements.

Quick selection can be solved TopK Elements problem, because after finding Kth Element, once again traverse the array, all less than or equal elements Kth Element is TopK Elements.

It can be seen quickly select and heap sort can be solved Kth Element and TopK Elements problems.

1. Kth Element

215. Kth Largest Element in an Array (Medium)

Input: [3,2,1,5,6,4] and k = 2
Output: 5

Topic Description: Find the inverse of the k-th element.

Sort : time complexity O (NlogN), the spatial complexity is O (1)

public int findKthLargest(int[] nums, int k) {
    Arrays.sort(nums); return nums[nums.length - k]; }

Heap : time complexity O (NlogK), the space complexity O (K).

public int findKthLargest ( int [] the nums, int K) { PriorityQueue < Integer> PQ = new new PriorityQueue <> (); // small stack top for ( int Val : the nums) PQ { .add (Val); IF (PQ . size () > K) // stack size is maintained PQ K .poll ();} return PQ .peek ();}

Quick Select : time complexity of O (N), the spatial complexity is O (1)

public int findKthLargest(int[] nums, int k) {
    k = nums.length - k; int l = 0, h = nums.length - 1; while (l < h) { int j = partition(nums, l, h); if (j == k) { break; } else if (j < k) { l = j + 1; } else { h = j - 1; } } return nums[k]; } private int partition(int[] a, int l, int h) { int i = l, j = h + 1; while (true) { while (a[++i] < a[l] && i < h) ; while (a[--j] > a[l] && j > l) ; if (i >= j) { break; } swap(a, i, j); } swap(a, l, j); return j; } private void swap(int[] a, int i, int j) { int t = a[i]; a[i] = a[j]; a[j] = t; }

Bucket sort

1. The most - k elements

347. Top K Frequent Elements (Medium)

Given [1,1,1,2,2,3] and k = 2, return [1,2].

Setting a plurality of buckets, each bucket same frequency number is stored appears. The subscript number represents the frequency of the tub appear, i.e. the frequency of the i-th number stored in the tub to occur i.

After the number are placed in barrels, buckets traversal from back to front, the number k is the first to get the most number of frequencies k appear.

public List<Integer> topKFrequent(int[] nums, int k) {
    Map<Integer, Integer> frequencyForNum = new HashMap<>(); for (int num : nums) { frequencyForNum.put(num, frequencyForNum.getOrDefault(num, 0) + 1); } List<Integer>[] buckets = new ArrayList[nums.length + 1]; for (int key : frequencyForNum.keySet()) { int frequency = frequencyForNum.get(key); if (buckets[frequency] == null) { buckets[frequency] = new ArrayList<>(); } buckets[frequency].add(key); } List<Integer> topK = new ArrayList<>(); for (int i = buckets.length - 1; i >= 0 && topK.size() < k; i--) { if (buckets[i] == null) { continue; } if (buckets[i].size() <= (k - topK.size())) { topK.addAll(buckets[i]); } else { topK.addAll(buckets[i].subList(0, k - topK.size())); } } return topK; }

2. The number of characters appear in sort of a string

451. Sort Characters By Frequency (Medium)

Input:
"tree"

Output:
"eert"

Explanation:
'e' appears twice while 'r' and 't' both appear once.
So 'e' must appear before both 'r' and 't'. Therefore "eetr" is also a valid answer.
public String frequencySort(String s) {
    Map<Character, Integer> frequencyForNum = new HashMap<>(); for (char c : s.toCharArray()) frequencyForNum.put(c, frequencyForNum.getOrDefault(c, 0) + 1); List<Character>[] frequencyBucket = new ArrayList[s.length() + 1]; for (char c : frequencyForNum.keySet()) { int f = frequencyForNum.get(c); if (frequencyBucket[f] == null) { frequencyBucket[f] = new ArrayList<>(); } frequencyBucket[f].add(c); } StringBuilder str = new StringBuilder(); for (int i = frequencyBucket.length - 1; i >= 0; i--) { if (frequencyBucket[i] == null) { continue; } for (char c : frequencyBucket[i]) { for (int j = 0; j < i; j++) { str.append(c); } } } return str.toString(); }

Dutch flag issue

Dutch flag contains three colors: red, white and blue.

There are three colored balls, the goal of the algorithm is these three ball correctly arranged in color order. It is actually a variant of the three-segmentation quicksort, three minutes to cut quick sort, each array are segmented into three sections: splitting element is smaller than, equal splitting element, the element is greater than the segmentation, the algorithm is the array and divided into three sections: equal red, white is equal, equal to blue.

 

1. sorting by color

75. Sort Colors (Medium)

Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Subject description: 0/1/2 only three colors.

public void sortColors(int[] nums) {
    int zero = -1, one = 0, two = nums.length; while (one < two) { if (nums[one] == 0) { swap(nums, ++zero, one++); } else if (nums[one] == 2) { swap(nums, --two, one); } else { ++one; } } } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; }

Guess you like

Origin www.cnblogs.com/daimasanjiaomao/p/11009070.html