【實戰】如何使用 Python 從 Redis 中刪除 4000萬 KEY
阿新 • • 發佈:2022-05-03
1.解決的問題:
一個數組中,其左右邊界都可以向右滑動,根據視窗的左右邊界滑動更新該視窗內的最大值(時間複雜度為O(1))
2.實現思路:
使用一個雙端佇列來維護:(處理的資料是陣列的下標,而不是數本身)
* 1.對於右邊界向右滑動一格,如果新增進來的元素比雙端佇列的隊尾元素小,則直接加入。否則,則彈出當前隊尾元素,
* 直到新增進來的元素小於隊尾元素為止。
* 2.對於左邊界向左滑動一格,如果被移走的左邊界元素是隊頭元素,則彈出該隊頭元素。否則,不進行任何操作
3.程式碼實現:
1 public static class WindowMax{ 2 privateint L; 3 private int R; 4 private int[] arr;//arr[L...R] 5 private LinkedList<Integer> qmax; 6 7 public WindowMax(int[] a) { 8 arr = a; 9 L = -1; 10 R = 0; 11 qmax = new LinkedList<>(); 12 }13 14 public void addNumFromRight() { 15 if (R == arr.length) { 16 return; 17 } 18 while (!qmax.isEmpty() && arr[R] >= arr[qmax.peekLast()]) { 19 qmax.pollLast(); 20 } 21 qmax.addLast(R);22 R++; 23 } 24 25 public void removeNumFromLeft() { 26 if (L >= R - 1) { 27 return; 28 } 29 L++; 30 if (L == qmax.peekFirst()) { 31 qmax.pollFirst(); 32 } 33 } 34 35 public Integer getMax() { 36 if (!qmax.isEmpty()) { 37 return arr[qmax.peekFirst()]; 38 } 39 return null; 40 } 41 }
4.運用該結構解決一個特例問題:
給定一個數組arr,視窗長度為3,從第一格開始依次向右移動,求出每次移動的視窗的最大值,最終結果用一個數組表示
程式碼:
1 public static int[] getWindowResult(int[] arr) { 2 WindowMax window = new WindowMax(arr); 3 for (int i = 0; i < 3; i++) { 4 window.addNumFromRight(); 5 } 6 int[] result = new int[arr.length - 2]; 7 for (int i = 0; i < arr.length - 2; i++) { 8 result[i] = window.getMax(); 9 window.addNumFromRight(); 10 window.removeNumFromLeft(); 11 } 12 return result; 13 }