題目詳情:
給你一個下標從 0 開始的整數數組 nums 以及一個目標元素 target 。
目標下標 是一個滿足 nums[i] == target 的下標 i 。
將 nums 按 非遞(di)減 順序(xu)(xu)排序(xu)(xu)后(hou),返回(hui)由 nums 中目標(biao)(biao)下標(biao)(biao)組成的列表(biao)。如(ru)果不存(cun)在目標(biao)(biao)下標(biao)(biao),返回(hui)一(yi)個(ge) 空(kong) 列表(biao)。返回(hui)的列表(biao)必(bi)須按 遞(di)增(zeng) 順序(xu)(xu)排列。
示例:
輸入:nums = [1,2,5,2,3], target = 2
輸出:[1,2]
解釋:排序后,nums 變為 [1,2,2,3,5] 。
滿(man)足 nums[i] == 2 的下標是 1 和 2 。
解題思路:
首先可以對nums進行遞增排序得到indexedNums。
然后,遍歷排序后的映射數組 indexedNums ,如果值與目標元素相等,則將索引加入到 sortedIndices 列表中。
最終返回 sortedIndices 列表即為滿足條(tiao)件的(de)索(suo)引(yin)列表,按(an)照(zhao)遞增順序排列。
代碼實現:
function searchTargetIndex(nums, target) {
const sortedIndices = [];
// 構建索引與值的映射數組
const indexedNums = nums.sort((a, b) => a - b);
// 遍歷排序后的映射(she)數組,記錄滿(man)足條件的索引
for (let index = 0; index < indexedNums.length; index++) {
const element = indexedNums[index];
if (element === target) {
sortedIndices.push(index);
}
}
return sortedIndices;
}
// 示例輸入
const nums = [48, 90, 9, 21, 31, 35, 19, 69, 29, 52, 100, 54, 21, 86, 6, 45, 42, 5, 62, 77, 15, 38];
const target = 6;
// 調用函數并輸出結果
console.log(searchTargetIndex(nums, target));