Find Target Indices After Sorting Array

easy binary search sorting

Problem

You are given an array of integers nums and an integer target. Imagine the array is sorted in non-decreasing order. A target index is any position in this sorted array that holds the value target. Return a list of all target indices, sorted in increasing order. If target does not appear in nums, return an empty list.

Inputnums = [1, 2, 5, 2, 3], target = 2
Output[1, 2]
Sorted, nums becomes [1, 2, 2, 3, 5]. The value 2 sits at positions 1 and 2, so the target indices are [1, 2].

def target_indices(nums, target):
    nums.sort()
    lo, hi = 0, len(nums)
    while lo < hi:
        mid = (lo + hi) // 2
        if nums[mid] < target:
            lo = mid + 1
        else:
            hi = mid
    res = []
    while lo < len(nums) and nums[lo] == target:
        res.append(lo)
        lo += 1
    return res
function targetIndices(nums, target) {
  nums.sort((a, b) => a - b);
  let lo = 0, hi = nums.length;
  while (lo < hi) {
    const mid = (lo + hi) >> 1;
    if (nums[mid] < target) lo = mid + 1;
    else hi = mid;
  }
  const res = [];
  while (lo < nums.length && nums[lo] === target) {
    res.push(lo);
    lo += 1;
  }
  return res;
}
class Solution {
    public List<Integer> targetIndices(int[] nums, int target) {
        Arrays.sort(nums);
        int lo = 0, hi = nums.length;
        while (lo < hi) {
            int mid = (lo + hi) >>> 1;
            if (nums[mid] < target) lo = mid + 1;
            else hi = mid;
        }
        List<Integer> res = new ArrayList<>();
        while (lo < nums.length && nums[lo] == target) {
            res.add(lo);
            lo += 1;
        }
        return res;
    }
}
vector<int> targetIndices(vector<int>& nums, int target) {
    sort(nums.begin(), nums.end());
    int lo = 0, hi = (int)nums.size();
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (nums[mid] < target) lo = mid + 1;
        else hi = mid;
    }
    vector<int> res;
    while (lo < (int)nums.size() && nums[lo] == target) {
        res.push_back(lo);
        lo += 1;
    }
    return res;
}
Time: O(n log n) Space: O(1)