置頂

我的 VPython 教學文件 (HackMD 版本)

VPython 教學文件目錄 安裝及測試 基本語法 等速度直線運動 自由落下 終端速度 水平抛射 使用For迴圈計算水平抛射資料 斜向抛射 圓周運動 簡諧運動 單擺 木塊彈簧系統分離 重力及簡諧 行星運動 相疊木塊 雙重簡諧運動 一維彈性碰撞 ...

熱門文章

2026年10月19日 星期一

LeetCode 解題筆記:2089. Find Target Indices After Sorting Array

作者:王一哲
日期:2026年10月19日


LeetCode 題目連結:2089. Find Target Indices After Sorting Array

解題想法


簡單題。題目給一個長度為 $n ~(1 \leq n \leq 100)$ 的正整數陣列 $nums ~(1 \leq nums[i] \leq 100)$,以及一個正整數 $target ~(1 \leq target \leq 100)$,要找出 $nums$ 由小到大排序之後 $target$ 的索引值。

這題最直接的想法就是將 $nums$ 排序,再用線性搜尋法或是二分搜尋法找出 $target$ 在 $nums$ 之中的索引值,由於 $n$ 最多為 $100$,線性搜尋法的速度很快。但其實這題根本不需要排序,只要用一個 for 迴圈掃過 $nums$,記錄小於 $target$ 的數字數量 $small$ 以及等於 $target$ 的數字數量 $equal$,再建立一個長度為 $equal$、內容為 $small$ 到 $small + equal - 1$ 的陣列即可。

Python 程式碼


線性搜尋法。Runtime: 0 ms, beats 100.00%. Memory: 19.38 MB, beats 24.20%.
class Solution:
    def targetIndices(self, nums: List[int], target: int) -> List[int]:
        nums.sort()
        ans = []
        for i, num in enumerate(nums):
            if num == target:
                ans.append(i)
        return ans


二分搜尋法。Runtime: 1 ms, beats 33.47%. Memory: 19.41 MB, beats 24.20%.
from bisect import bisect_left

class Solution:
    def targetIndices(self, nums: list[int], target: int) -> list[int]:
        n = len(nums)  # 長度
        nums.sort()  # 排序
        ans = []  # 答案
        # 用二分搜尋法從 nums 之中找第一個大於、等於 target 的索引值
        idx = bisect_left(nums, target)
        if idx < n:  # 有找到索引值,要再向後找,只找等於 target 的項目
            while idx < n and nums[idx] == target:
                ans.append(idx)
                idx += 1
        return ans


計算數量。Runtime: 0 ms, beats 100.00%. Memory: 19.21 MB, beats 62.71%.
class Solution:
    def targetIndices(self, nums: list[int], target: int) -> list[int]:
        small = 0  # 小於 target 的數量
        equal = 0  # 等於 target 的數量
        for num in nums:
            if num < target:
                small += 1
            elif num == target:
                equal += 1
        return list(range(small, small + equal))


C++ 程式碼


線性搜尋法。Runtime: 0 ms, beats 100.00%. Memory: 15.26 MB, beats 16.50%.
class Solution {
public:
    vector<int> targetIndices(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int n = (int)nums.size();
        vector<int> ans;
        for(int i = 0; i < n; i++) {
            if (nums[i] == target) {
                ans.push_back(i);
            }
        }
        return ans;
    }
};


二分搜尋法。Runtime: 0 ms, beats 100.00%. Memory: 15.00 MB, beats 86.46%.
class Solution {
public:
    vector<int> targetIndices(vector<int>& nums, int target) {
        int n = (int)nums.size();  // 長度
        sort(nums.begin(), nums.end());  // 排序
        vector<int> ans;  // 答案
        // 用二分搜尋法從 nums 之中找第一個大於、等於 target 的索引值
        int idx = lower_bound(nums.begin(), nums.end(), target) - nums.begin();
        if (idx < n) {  // 有找到索引值,要再向後找,只找等於 target 的項目
            while(idx < n && nums[idx] == target) {
                ans.push_back(idx);
                idx++;
            }
        }
        return ans;
   }
};


計算數量。Runtime: 0 ms, beats 100.00%. Memory: 15.10 MB, beats 86.46%.
class Solution {
public:
    vector<int> targetIndices(vector<int>& nums, int target) {
        int small = 0, equal = 0;  // 小於 target 的數量,等於 target 的數量
        for(int num : nums) {
            if (num < target) {
                small++;
            } else if (num == target) {
                equal++;
            }
        }
        // 填入答案 small ~ small + equal - 1
        vector<int> ans;
        for(int i = small; i < small + equal; i++) {
            ans.push_back(i);
        }
        return ans;
   }
};


C 語言程式碼


計算數量。Runtime: 0 ms, beats 100.00%. Memory: 9.22 MB, beats 92.78%.
/**
 * Note: The returned array must be malloced, assume caller calls free().
 */
int* targetIndices(int* nums, int numsSize, int target, int* returnSize) {
    int small = 0, equal = 0;  // 小於 target 的數量,等於 target 的數量
    for(int i = 0; i < numsSize; i++) {
        if (nums[i] < target) {
            small++;
        } else if (nums[i] == target) {
            equal++;
        }
    }
    // 填入答案 small ~ small + equal - 1
    int* ans = (int*)malloc(equal * sizeof(int));
    *returnSize = equal;
    for(int i = 0; i < equal; i++) {
        ans[i] = small + i;
    }
    return ans;
}


沒有留言:

張貼留言