更正:
每次更新时,将最值也更新。
// Query of min time: O(1)
public int getMin() { return this.min; }
============================
抛砖引玉,欢迎批评,期待更好的解法。
采用TreeMap,使用数组的值作key,同一值可能有重复,对应的indices组成的HashSet
作value。
更新:O(logn),查询最值:O(logn)。
import java.util.*;
class AccessMinAndUpdateOfArray {
private int min = Integer.MAX_VALUE;
private int[] a;
private TreeMap> tm;
// Initialization time: O(nlogn).
public AccessMinAndUpdateOfArray(int[] a) {
this.a = a;
tm = new TreeMap<>();
for (int i = 0; i < a.length; i) {
this.min = Math.min(a[i], this.min);
tm.computeIfAbsent(a[i], s -> new HashSet<>()).add(i);
}
}
// Query of min time: O(logn).
public int getMin() { return tm.firstEntry().getKey(); }
// Update time: O(logn).
public void update(int id, int val) { // update a[id] with val.
if (val == a[id]) { return; } // same value, nothing to do.
// remove old value - 2 cases: multiple/one
// element(s) with value of a[id] in a.
if (tm.get(a[id]).size() > 1) { tm.get(a[id]).remove(id); }
else { tm.remove(a[id]); } // only 1 value of a[id] in a.
// add new value.
tm.computeIfAbsent(val, s -> new HashSet<>()).add(id);
this.a[id] = val;
this.min = Math.min(val, this.min);
}
}