Leetcode 34. Find First and Last Position of Element in Sorted Array

  1. create an result array, assign the default result
  2. scan through the array and put the first and last target number in the result.
  1. know how to use binary search to let the time complexity to O(log n)
  2. trick part in binary search, know how to twist “mid” to make sure it won’t stuck in same number
  1. first, I want to find the most left target. So I will be no mercy on right number, if the mid number equal to target, I will keep pushing it. On the other hand, if the start pointer find the target, it will keep adding until the end.
  2. using different color dots to image the target and mid number.
  3. if it’s hard to imagine, try iterate example.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Gary Chiang

Gary Chiang

CS new grad, 6 years experience related to supply chain management. Located in Bay area