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 = std::count(begin(nums), end(nums), target);
    int lessThan =
        count_if(begin(nums), end(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)]
Back to top