返回介绍

solution / 1000-1099 / 1064.Fixed Point / README_EN

发布于 2024-06-17 01:03:31 字数 3519 浏览 0 评论 0 收藏 0

1064. Fixed Point

中文文档

Description

Given an array of distinct integers arr, where arr is sorted in ascending order, return the smallest index i that satisfies arr[i] == i. If there is no such index, return -1.

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Constraints:

  • 1 <= arr.length < 104
  • -109 <= arr[i] <= 109

 

Follow up: The O(n) solution is very straightforward. Can we do better?

Solutions

Solution 1

class Solution:
  def fixedPoint(self, arr: List[int]) -> int:
    left, right = 0, len(arr) - 1
    while left < right:
      mid = (left + right) >> 1
      if arr[mid] >= mid:
        right = mid
      else:
        left = mid + 1
    return left if arr[left] == left else -1
class Solution {
  public int fixedPoint(int[] arr) {
    int left = 0, right = arr.length - 1;
    while (left < right) {
      int mid = (left + right) >> 1;
      if (arr[mid] >= mid) {
        right = mid;
      } else {
        left = mid + 1;
      }
    }
    return arr[left] == left ? left : -1;
  }
}
class Solution {
public:
  int fixedPoint(vector<int>& arr) {
    int left = 0, right = arr.size() - 1;
    while (left < right) {
      int mid = left + right >> 1;
      if (arr[mid] >= mid) {
        right = mid;
      } else {
        left = mid + 1;
      }
    }
    return arr[left] == left ? left : -1;
  }
};
func fixedPoint(arr []int) int {
  left, right := 0, len(arr)-1
  for left < right {
    mid := (left + right) >> 1
    if arr[mid] >= mid {
      right = mid
    } else {
      left = mid + 1
    }
  }
  if arr[left] == left {
    return left
  }
  return -1
}
function fixedPoint(arr: number[]): number {
  let left = 0;
  let right = arr.length - 1;
  while (left < right) {
    const mid = (left + right) >> 1;
    if (arr[mid] >= mid) {
      right = mid;
    } else {
      left = mid + 1;
    }
  }
  return arr[left] === left ? left : -1;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文