2089. Find Target Indices After Sorting Array

LeetCode 力扣

1. Description

Given an integer array nums with zero-based indices and an integer target, sort nums in non-decreasing order.
Return every index at which the sorted array contains target, listing the indices in ascending order. Return an empty list if target does not occur.

2. Example

Example 1

Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: Sorting produces [1,2,2,3,5], where the two occurrences of 2 occupy indices 1 and 2.

Example 2

Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: Sorting produces [1,2,2,3,5], where 3 occupies index 3.

Example 3

Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: Sorting produces [1,2,2,3,5], where 5 occupies index 4.

3. Constraints

  • 1 <= nums.length <= 100
  • 1 <= nums[i], target <= 100

4. Solutions

n = nums.size()
Time complexity: O(n log n)
Space complexity: O(log n)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution {
public:
    vector<int> targetIndices(vector<int> &nums, int target) {
        sort(nums.begin(), nums.end());

        auto left = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        auto right = upper_bound(nums.begin(), nums.end(), target) - nums.begin();

        vector<int> indexes;
        for (int i = left; i < right; ++i) {
            indexes.push_back(i);
        }

        return indexes;
    }
};
comments powered by Disqus