codewars:Element equals its index

Element equals its index

Instructions

Given a sorted array of distinct integers, write a function index_equals_value that returns the lowest index for which array[index] == index.
Return -1 if there is no such index.Your algorithm should be very performant.[input] array of integers ( with 0-based nonnegative indexing )
[output] integerExamples:

Examples:

input: [-8,0,2,5]
output: 2 # since array[2] == 2

input: [-1,0,3,6]
output: -1 # since no index in array satisfies array[index] == index

Random Tests Constraints:

Array length: 200 000
Amount of tests: 1 000
Time limit: 1.5 s

我的代码

我是采用了二分法查找来解决这道题目的,然后我看了以下大多数的解法都是用了二分法,当然我的方法并不是最简单的。

def index_equals_value(arr):
    beg=0
    end=len(arr)
    ls=[]
    if arr[0]==0:
        return 0
    if arr[0]>0:
        return -1
    while end-beg>1:
        mid=(beg+end)//2
        if arr[mid]==mid:
             ls.append(mid)
             end=mid
        elif arr[mid]>mid:
            end=mid
        elif arr[mid]<mid:
            beg=mid
    return min(ls) if len(ls)>0 else -1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zhanghp947

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值