| | 1 | | // -------------------------------------------------------------------------------- |
| | 2 | | // Copyright (C) 2025 Eugene Eremeev (also known as Yevhenii Yeriemeieiv). |
| | 3 | | // All Rights Reserved. |
| | 4 | | // -------------------------------------------------------------------------------- |
| | 5 | | // This software is the confidential and proprietary information of Eugene Eremeev |
| | 6 | | // (also known as Yevhenii Yeriemeieiv) ("Confidential Information"). You shall not |
| | 7 | | // disclose such Confidential Information and shall use it only in accordance with |
| | 8 | | // the terms of the license agreement you entered into with Eugene Eremeev (also |
| | 9 | | // known as Yevhenii Yeriemeieiv). |
| | 10 | | // -------------------------------------------------------------------------------- |
| | 11 | |
|
| | 12 | | namespace LeetCode.Algorithms.BinarySearch; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class BinarySearchExact : IBinarySearch |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(log n) |
| | 19 | | /// Space complexity - O(1) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="target"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public int Search(int[] nums, int target) |
| 3 | 25 | | { |
| 3 | 26 | | var left = 0; |
| 3 | 27 | | var right = nums.Length - 1; |
| | 28 | |
|
| 7 | 29 | | while (left <= right) |
| 6 | 30 | | { |
| 6 | 31 | | var mid = left + ((right - left) / 2); |
| | 32 | |
|
| 6 | 33 | | if (nums[mid] == target) |
| 2 | 34 | | { |
| 2 | 35 | | return mid; |
| | 36 | | } |
| | 37 | |
|
| 4 | 38 | | if (nums[mid] > target) |
| 1 | 39 | | { |
| 1 | 40 | | right = mid - 1; |
| 1 | 41 | | } |
| | 42 | | else |
| 3 | 43 | | { |
| 3 | 44 | | left = mid + 1; |
| 3 | 45 | | } |
| 4 | 46 | | } |
| | 47 | |
|
| 1 | 48 | | return -1; |
| 3 | 49 | | } |
| | 50 | | } |