Skip to content

2089. Find Target Indices After Sorting Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> targetIndices(vector<int>& nums, int target) {
    vector<int> ans;
    const int count = ranges::count(nums, target);
    int lessThan =
        ranges::count_if(nums, [&](int num) { return num < target; });

    for (int i = 0; i < count; ++i)
      ans.push_back(lessThan++);

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Solution {
  public List<Integer> targetIndices(int[] nums, int target) {
    List<Integer> ans = new ArrayList<>();
    final int count = (int) Arrays.stream(nums).filter(num -> num == target).count();
    int lessThan = (int) Arrays.stream(nums).filter(num -> num < target).count();

    for (int i = 0; i < count; ++i)
      ans.add(lessThan++);

    return ans;
  }
}
1
2
3
4
5
class Solution:
  def targetIndices(self, nums: list[int], target: int) -> list[int]:
    count = nums.count(target)
    lessThan = sum(num < target for num in nums)
    return [i for i in range(lessThan, lessThan + count)]