📅  最后修改于: 2023-12-03 15:41:17.505000             🧑  作者: Mango
给定一个长度为n的数组nums和两个整数left、right,返回在区间[left,right]中第一个不等于x的下标,若该下标不存在,则返回-1。
遍历[left,right]中的每个数,找到第一个不等于x的下标。
时间复杂度:O(right-left+1)
利用二分法查找数组中第一个不等于x的下标。
时间复杂度:O(log(right-left+1))
代码实现如下:
/**
* 给定一个数组nums和两个整数left、right
* 返回在区间[left,right]中第一个不等于x的下标,若该下标不存在,则返回-1
*/
public int findFirstIndex(int[] nums, int left, int right, int x) {
if (nums == null || left > right || left < 0 || right >= nums.length) {
return -1;
}
int l = left, r = right;
while (l <= r) {
int mid = l + (r - l) / 2;
if (nums[mid] == x) {
l = mid + 1;
} else if (nums[mid] > x) {
r = mid - 1;
} else {
if (mid == left || nums[mid - 1] != x) {
return mid;
}
r = mid - 1;
}
}
return -1;
}
int[] nums = {1, 2, 3, 4, 5};
int left = 1, right = 3, x = 3;
int expected = 2;
int result = findFirstIndex(nums, left, right, x);
Assert.assertEquals(expected, result);
int[] nums = {1, 2, 3, 4, 5};
int left = 1, right = 3, x = 6;
int expected = -1;
int result = findFirstIndex(nums, left, right, x);
Assert.assertEquals(expected, result);
int[] nums = {1, 2, 2, 4, 5};
int left = 1, right = 3, x = 2;
int expected = -1;
int result = findFirstIndex(nums, left, right, x);
Assert.assertEquals(expected, result);
int[] nums = {1, 2, 2, 4, 5};
int left = 1, right = 3, x = 1;
int expected = 0;
int result = findFirstIndex(nums, left, right, x);
Assert.assertEquals(expected, result);
本文介绍了两种方法解决给定索引范围内不等于x的最小索引的问题。较为高效快速的方式是采用二分查找法。在测试用例中展示了方法的操作,并展示了算法有很好的可扩展性。