You are given a 0-indexed integer array nums having length n, an integer indexDifference, and an integer valueDifference.
Your task is to find two indices i and j, both in the range [0, n -1], that satisfy the following conditions:
abs(i - j) >= indexDifference, and
abs(nums[i] - nums[j]) >= valueDifference
Return an integer arrayanswer, whereanswer = [i, j]if there are two such indices , andanswer = [-1, -1]otherwise. If there are multiple choices for the two indices, return any of them.
Input: nums =[5,1,4,1], indexDifference =2, valueDifference =4Output: [0,3]Explanation: In this example, i =0 and j =3 can be selected.abs(0-3)>=2 and abs(nums[0]- nums[3])>=4.Hence, a valid answer is[0,3].[3,0]is also a valid answer.
Input: nums =[2,1], indexDifference =0, valueDifference =0Output: [0,0]Explanation: In this example, i =0 and j =0 can be selected.abs(0-0)>=0 and abs(nums[0]- nums[0])>=0.Hence, a valid answer is[0,0].Other valid answers are [0,1],[1,0], and [1,1].
Input: nums =[1,2,3], indexDifference =2, valueDifference =4Output: [-1,-1]Explanation: In this example, it can be shown that it is impossible to find two indices that satisfy both conditions.Hence,[-1,-1]is returned.
The problem asks for any pair of indices (i, j) such that the absolute difference of their indices is at least indexDifference and the absolute difference of their values is at least valueDifference. Since the constraints are small, we can check all possible pairs.
classSolution {
publicint[]findIndices(int[] nums, int indexDifference, int valueDifference) {
int n = nums.length;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (Math.abs(i - j) >= indexDifference && Math.abs(nums[i]- nums[j]) >= valueDifference)
returnnewint[]{i, j};
}
}
returnnewint[]{-1, -1};
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funfindIndices(nums: IntArray, indexDifference: Int, valueDifference: Int): IntArray {
val n = nums.size
for (i in0 until n) {
for (j in0 until n) {
if (kotlin.math.abs(i - j) >= indexDifference && kotlin.math.abs(nums[i] - nums[j]) >= valueDifference)
return intArrayOf(i, j)
}
}
return intArrayOf(-1, -1)
}
}
1
2
3
4
5
6
7
8
classSolution:
deffindIndices(self, nums: list[int], indexDifference: int, valueDifference: int) -> list[int]:
n = len(nums)
for i in range(n):
for j in range(n):
if abs(i - j) >= indexDifference and abs(nums[i] - nums[j]) >= valueDifference:
return [i, j]
return [-1, -1]
1
2
3
4
5
6
7
8
9
10
11
12
13
impl Solution {
pubfnfind_indices(nums: Vec<i32>, index_difference: i32, value_difference: i32) -> Vec<i32> {
let n = nums.len();
for i in0..n {
for j in0..n {
if (i asi32- j asi32).abs() >= index_difference && (nums[i] - nums[j]).abs() >= value_difference {
returnvec![i asi32, j asi32];
}
}
}
vec![-1, -1]
}
}