---
# System prepended metadata

title: Leetcode 2089. Find Target Indices After Sorted Array
tags: [Leetcode, Binary Search]

---

## 題解

### 二分搜索鎖定左右邊界計算有多少

```python=
class Solution:
    def targetIndices(self, nums: List[int], target: int) -> List[int]:
        nums = sorted(nums)
        n = len(nums)
        output = []

        def binary_search(bound: bool):
            nonlocal n,target,nums
            left, right = 0, n - 1
            ans = -1

            while left <= right:
                mid = left + (right - left) // 2
                if nums[mid] == target:
                    ans = mid
                    if bound:
                        left = mid + 1
                    else:
                        right = mid - 1
                else:
                    if nums[mid] > target:
                        right = mid - 1
                    else:
                        left = mid + 1
            return ans
        
        left_bound = binary_search(False)
        if left_bound == -1:
            return []
        right_bound = binary_search(True)
        for i in range(left_bound,right_bound+1):
            output.append(i)
        
        return output
```