美文网首页
Closest In Sorted Array in Pytho

Closest In Sorted Array in Pytho

作者: GakkiLove | 来源:发表于2018-03-29 21:13 被阅读0次

    Given a target integer T and an integer array A sorted in ascending order, find the index i in A such that A[i] is closest to T.

    Assumptions:

    There can be duplicate elements in the array, and we can return any of the indices with same value.

    Examples:

    A = {1, 2, 3}, T = 2, return 1
    A = {1, 4, 6}, T = 3, return 1
    A = {1, 4, 6}, T = 5, return 1 or 2
    A = {1, 3, 3, 4}, T = 2, return 0 or 1 or 2

    def find_closest_num(nums,target):
      if len(nums) == 0:
        return -1
      left = 0
      right = len(nums) - 1
      while left < right - 1:
        mid = (left + right)/2
        if nums[mid] > target:
          right = mid
        elif nums[mid] < target:
          left = mid
        else:
          return mid
      return left if abs(nums[left] - target) < abs(nums[right] - target) else right

    相关文章

      网友评论

          本文标题:Closest In Sorted Array in Pytho

          本文链接:https://www.haomeiwen.com/subject/qrmvcftx.html