In the first iteration, record the position of each number. Sort the array and check if close numbers have close indices.

```
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
if (map.containsKey(nums[i]) &&
0 <= t && i - map.get(nums[i]) <= k) {
return true;
}
map.put(nums[i], i);
}
Arrays.sort(nums);
for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] - nums[i] > 0 && nums[j] - nums[i] <= t) {
if (Math.abs(map.get(nums[j]) - map.get(nums[i])) <= k) {
return true;
}
} else {
break;
}
}
}
return false;
```