魔术索引
难度:
标签:
题目描述
A magic index in an array A[0...n-1]
is defined to be an index such that A[i] = i
. Given a sorted array of integers, write a method to find a magic index, if one exists, in array A. If not, return -1. If there are more than one magic index, return the smallest one.
Example1:
Input: nums = [0, 2, 3, 4, 5] Output: 0
Example2:
Input: nums = [1, 1, 1] Output: 1
Note:
1 <= nums.length <= 1000000
- This problem is the follow-up of the original problem in the book, i.e. the values are not distinct.
代码结果
运行时间: 18 ms, 内存: 16.9 MB
// 思路: 使用Java Stream API,通过IntStream.range遍历数组并找到第一个满足A[i] = i的索引。
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class MagicIndexStream {
public int findMagicIndex(int[] nums) {
OptionalInt magicIndex = IntStream.range(0, nums.length)
.filter(i -> nums[i] == i)
.findFirst();
return magicIndex.orElse(-1);
}
public static void main(String[] args) {
MagicIndexStream mis = new MagicIndexStream();
int[] nums1 = {0, 2, 3, 4, 5};
int[] nums2 = {1, 1, 1};
System.out.println(mis.findMagicIndex(nums1)); // 输出: 0
System.out.println(mis.findMagicIndex(nums2)); // 输出: 1
}
}
解释
方法:
此题解采用了直接的线性搜索方法。从数组的第一个元素开始遍历,一旦发现某个索引i满足条件nums[i] == i,即判断为魔术索引,立即返回该索引。如果遍历完整个数组都没有找到符合条件的索引,则返回-1。
时间复杂度:
O(n)
空间复杂度:
O(1)
代码细节讲解
🦆
在有序数组中寻找特定条件的值时,为什么选择使用线性搜索而不是二分搜索来提高查找效率?
▷🦆
对于含有重复元素的数组,线性搜索方法在遇到重复值时能够有效地找到最小的魔术索引吗?
▷🦆
如果数组中的元素值大于当前索引值,线性搜索是否还需要继续向后查找?
▷