题目
给你一个下标从 0 开始的整数数组 nums 以及一个目标元素 target 。
目标下标 是一个满足 nums[i] == target 的下标 i 。
将 nums 按 非递减 顺序排序后,返回由 nums 中目标下标组成的列表。如果不存在目标下标,返回一个 空 列表。返回的列表必须按 递增 顺序排列。
思路
- 在排序后的数组中,前cnt1个元素比target小,=target的元素(存在)下标即连续,从cnt1开始计算
代码
class Solution {
public:
vector<int> targetIndices(vector<int>& nums, int target) {
int cnt1 = 0;
int cnt2 = 0;
for (const int num : nums) {
if (!(num ^ target)) ++cnt2;
else if (num < target) ++cnt1;
}
vector<int>ret;
for (int i = cnt1; i < cnt1 + cnt2; ++i) {
ret.push_back(i);
}
return ret;
}
};