Leetcode 2089. Find Target Indices After Sorting Array
You are given a 0-indexed
integer array nums
and an integer target
.
You need to return the indices
of the target in nums after sorting nums in non-decreasing
order. If there are no target indices, return an empty array. The returned array must be sorted in increasing order.
Example 1:
Input: nums = [1,2,5,2,3], target = 2
Output: [1,2]
Explanation: After sorting, nums is [1,2,2,3,5]. The indices where 2 is present in nums are 1 and 2.
Example 2:
Input: nums = [1,2,5,2,3], target = 3
Output: [3]
Explanation: After sorting, nums is [1,2,2,3,5]. The index where 3 is present in nums is 3.
Example 3:
Input: nums = [1,2,5,2,3], target = 5
Output: [4]
Explanation: After sorting, nums is [1,2,2,3,5]. The index where 5 is present in nums is 4.
1 <= nums.length <= 100
1 <= nums[i], target <= 100
#include <vector>
#include <algorithm>
std::vector<int> targetIndices(std::vector<int>& nums, int target) {
std::vector<int> result;
// Step 1: Sort the array in non-decreasing order
std::sort(nums.begin(), nums.end());
// Step 2: Iterate through the sorted array and collect indices where value equals target
for (int i = 0; i < nums.size(); ++i) {
if (nums[i] == target) {
result.push_back(i);
}
}
return result;
}
Thus, the overall time complexity of the solution is O(n log n).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?