亚欧色一区w666天堂,色情一区二区三区免费看,少妇特黄A片一区二区三区,亚洲人成网站999久久久综合,国产av熟女一区二区三区

  • 發布文章
  • 消息中心
點贊
收藏
評論
分享
原創

找出數組排序后的目標下標-算法學習

2023-07-12 04:00:48
4
0

題目詳情:
給你一個下標從 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));

0條評論
作者已關閉評論
t****m
98文(wen)章數
1粉絲數(shu)
t****m
98 文章(zhang) | 1 粉(fen)絲
t****m
98文章(zhang)數
1粉絲數(shu)
t****m
98 文章 | 1 粉絲(si)
原創

找出數組排序后的目標下標-算法學習

2023-07-12 04:00:48
4
0

題目詳情:
給你一個下標從 0 開始的整數數組 nums 以及一個目標元素 target 。
目標下標 是一個滿足 nums[i] == target 的下標 i 。
將 nums 按 非遞減 順(shun)序排(pai)序后(hou),返回(hui)(hui)由 nums 中(zhong)目標(biao)(biao)下(xia)標(biao)(biao)組成的列(lie)表(biao)。如(ru)果不存(cun)在目標(biao)(biao)下(xia)標(biao)(biao),返回(hui)(hui)一(yi)個(ge) 空 列(lie)表(biao)。返回(hui)(hui)的列(lie)表(biao)必須按 遞增 順(shun)序排(pai)列(lie)。

示例:
輸入:nums = [1,2,5,2,3], target = 2
輸出:[1,2]
解釋:排序后,nums 變為 [1,2,2,3,5] 。
滿(man)足 nums[i] == 2 的下(xia)標是 1 和 2 。

解題思路:
首先可以對nums進行遞增排序得到indexedNums。
然后,遍歷排序后的映射數組 indexedNums ,如果值與目標元素相等,則將索引加入到 sortedIndices 列表中。
最終返回 sortedIndices 列(lie)表(biao)即為滿(man)足(zu)條件的索引(yin)列(lie)表(biao),按照遞增順序排(pai)列(lie)。

代碼實現:
function searchTargetIndex(nums, target) {
    const sortedIndices = [];

    // 構建索引與值的映射數組
    const indexedNums = nums.sort((a, b) => a - b);

    // 遍歷排序后的映射數組,記錄滿足條件的索引

    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));

文章來自個人專欄
文(wen)章 | 訂閱
0條評論
作者已關閉評論
作者已關閉評論
0
0