有这样一个数组A,大小为n,相邻元素差的绝对值都是1,如A={4,5,6,5,6,7,8,9,10,9}。现在给定数组A和目标整数t,请找到t在数组中的位置。
比如我现在要找到9,9-4=5,那么中间的数都可以直接跳过去比较五个数之后的位置,其实就是遍历的同时跳过不需要考虑的数。
# -*- coding:utf-8 -*-
class Solution:
def find(self, array, target):
# write code here
length = len(array)
abs_length = abs(target-array[0])
if length == 0 or abs_length >= length:
return None
i = 0
while i < length:
if array[i] == target:
return i
else:
res = abs(target - array[i])
i += res
continue
return None
if __name__ == '__main__':
a = Solution()
array = [4,3,2,1,2,3,4,5,6,7]
target = 1
print(a.find(array, target))