| | 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.FindTargetIndicesAfterSortingArray; |
| | 13 | |
|
| | 14 | | /// <inheritdoc /> |
| | 15 | | public class FindTargetIndicesAfterSortingArrayBinarySearch : IFindTargetIndicesAfterSortingArray |
| | 16 | | { |
| | 17 | | /// <summary> |
| | 18 | | /// Time complexity - O(n log n) |
| | 19 | | /// Space complexity - O(k) |
| | 20 | | /// </summary> |
| | 21 | | /// <param name="nums"></param> |
| | 22 | | /// <param name="target"></param> |
| | 23 | | /// <returns></returns> |
| | 24 | | public IList<int> TargetIndices(int[] nums, int target) |
| 3 | 25 | | { |
| 3 | 26 | | Array.Sort(nums); |
| | 27 | |
|
| 3 | 28 | | var left = 0; |
| 3 | 29 | | var right = nums.Length - 1; |
| | 30 | |
|
| 10 | 31 | | while (left < right) |
| 7 | 32 | | { |
| 7 | 33 | | var mid = left + ((right - left) / 2); |
| | 34 | |
|
| 7 | 35 | | if (nums[mid] >= target) |
| 3 | 36 | | { |
| 3 | 37 | | right = mid; |
| 3 | 38 | | } |
| 4 | 39 | | else if (nums[mid] < target) |
| 4 | 40 | | { |
| 4 | 41 | | left = mid + 1; |
| 4 | 42 | | } |
| 7 | 43 | | } |
| | 44 | |
|
| 3 | 45 | | if (nums[left] != target) |
| 0 | 46 | | { |
| 0 | 47 | | return new List<int>(); |
| | 48 | | } |
| | 49 | |
|
| 3 | 50 | | var result = new List<int>(); |
| | 51 | |
|
| 7 | 52 | | while (left < nums.Length && nums[left] == target) |
| 4 | 53 | | { |
| 4 | 54 | | result.Add(left); |
| | 55 | |
|
| 4 | 56 | | left++; |
| 4 | 57 | | } |
| | 58 | |
|
| 3 | 59 | | return result; |
| 3 | 60 | | } |
| | 61 | | } |