1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| public class IndexTree { static int N, offset; static int[] maxTree, minTree;
public static void main(String[] args) { int[] nums = {1, 7, 2, 5, 3, 6}; N = nums.length; initTree(); for (int i = 0; i < N; i++) { update(i, nums[i]); } System.out.println(getMax(2, 4)); System.out.println(getMin(2, 4)); }
private static void initTree() { int n = 0; while ((1 << n) < N) n++; maxTree = new int[1 << (n + 1)]; minTree = new int[1 << (n + 1)]; Arrays.fill(minTree, Integer.MAX_VALUE);
offset = 1 << n; }
private static void update(int index, int value) { index = offset + index; while (index > 0) { maxTree[index] = Math.max(value, maxTree[index]); minTree[index] = Math.min(value, minTree[index]);
index >>= 1; } }
private static int getMax(int start, int end) { int max = 0; start = offset + start - 1; end = offset + end - 1; while (start <= end) { if ((start & 1) == 1) { max = Math.max(max, maxTree[start]); } if ((end & 1) == 0) { max = Math.max(max, maxTree[end]); } start = (start + 1) >> 1; end = (end - 1) >> 1; } return max; }
private static int getMin(int start, int end) { start = offset + start - 1; end = offset + end - 1; int min = Integer.MAX_VALUE; while (start <= end) { if ((start & 1) == 1) { min = Math.min(min, minTree[start]); } if ((end & 1) == 0) { min = Math.min(min, minTree[end]); } start = (start + 1) >> 1; end = (end - 1) >> 1; } return min; } }
|