题目
给你一个下标从 0 开始、长度为 n 的整数数组 nums ,以及整数 indexDifference 和整数 valueDifference 。
你的任务是从范围 [0, n - 1] 内找出 2 个满足下述所有条件的下标 i 和 j :
abs(i - j) >= indexDifference且abs(nums[i] - nums[j]) >= valueDifference
返回整数数组 answer。如果存在满足题目要求的两个下标,则 answer = [i, j] ;否则,answer = [-1, -1] 。如果存在多组可供选择的下标对,只需要返回其中任意一组即可。
注意: i 和 j 可能 相等 。
思路
在外循环固定左边的数据, 然后通过内循环找到差值大于 valueDifference 的下标.
返回这两个下标
package com.kirisaki;
import java.util.Arrays;
class Solution {
public int[] findIndices(int[] nums, int indexDifference, int valueDifference) {
int[] ans = new int[2];
Arrays.fill(ans, -1);
int index = 0;
int n = nums.length;
while (index + indexDifference <= n - 1) {
int temp = indexDifference;
while (index + temp <= n - 1) {
if (Math.abs(nums[index] - nums[index + temp++]) >= valueDifference){
ans[0] = index;
ans[1] = index + temp - 1;
return ans;
}
}
index++;
}
return ans;
}
}
存在问题
双层遍历会重复取出右边的数据,参考灵神的题解.通过存储最大值和最小值的下标来解决