Binary Search

4 years ago  •  By  •  0 Comments

 

Description

Binary search is a famous question in algorithm. For a given sorted array (ascending order) and a target number, find the first index of this number in O(log n) time complexity. If the target number does not exist in the array, return -1.

Example If the array is [1, 2, 3, 3, 4, 5, 10], for given target 3, return 2.

Problem Set

 Search Insert Position

DescriptionSolutionNote

Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

You may assume NO duplicates in the array.

Example:

  • [1,3,5,6], 5 → 2
  • [1,3,5,6], 2 → 1
  • [1,3,5,6], 7 → 4
  • [1,3,5,6], 0 → 0

 

Submit a Comment