[Leetcode 1064] Fixed Point

原题说明

Given an array A of distinct integers sorted in ascending order, return the smallest index i that satisfies A[i] == i.  Return -1 if no such i exists.

 

Example 1:

Input: [-10,-5,0,3,7]
Output: 3
Explanation:
For the given array, A[0] = -10, A[1] = -5, A[2] = 0, A[3] = 3, thus the output is 3.

Example 2:

Input: [0,2,5,8,17]
Output: 0
Explanation:
A[0] = 0, thus the output is 0.

Example 3:

Input: [-10,-5,3,4,7,9]
Output: -1
Explanation:
There is no such i that A[i] = i, thus the output is -1.

 

Note:

  1. 1 <= A.length < 10^4
  2. -10^9 <= A[i] <= 10^9

解题思路

因为给出的是一个排序的array,而index也是自然从0n-1的排序数组,因此本题采用二分法来查找A[i] == iindex
i < A[i], 我们往左边查找,当 i >= A[i]时, 我们往右边查找。
需要注意的因为要求最小的index,我们更新右端点时,需要 i >= A[i]。如果是最大的index, 则应该是 i > A[i]

示例代码 (cpp)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
public:
int fixedPoint(vector<int>& A) {
int left = 0;
int right = A.size() - 1;
while (left + 1 < right) {
int mid = left + (right - left) / 2;
if (A[mid] >= mid) {
right = mid;
}
else {
left = mid;
}
}
if (left == A[left]) {
return left;
}
if (right == A[right]) {
return right;
}
return -1;
}
};

示例代码 (java)

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public int fixedPoint(int[] A) {
int l = 0, r = A.length - 1;
while (l < r) {
int m = (l + r) / 2;
if (A[m] - m < 0)
l = m + 1;
else
r = m;
}
return A[l] == l ? l : -1;
}
}

示例代码 (python)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution(object):
def fixedPoint(self, A):
"""
:type A: List[int]
:rtype: int
"""
l, r = 0, len(A) - 1
while l < r:
m = (l + r) / 2
if A[m] - m < 0:
l = m + 1
else:
r = m
return l if A[l] == l else -1

复杂度分析

时间复杂度: O(logN)
空间复杂度: O(1)

视频讲解

我们在Youtube上更新了视频讲解,欢迎关注!

------ 关注公众号:猩猩的乐园 ------