置頂

GeoGebra 文章目錄

GeoGebra 文章目錄  更新日期:2018/2/8 我將 GeoGebra 相關的文章及檔案連結都整理在這篇裡,之後如果有新的文章也會同時更新這個目錄。上傳到 GeoGebraTube 的檔案,我有試著用 Google Chrome 63.0.3239.13...

熱門文章

2026年7月24日 星期五

LeetCode 解題筆記:3514. Number of Unique XOR Triplets II

作者:王一哲
日期:2026年7月24日


LeetCode 題目連結:3514. Number of Unique XOR Triplets II

解題想法


中等難度題。題目給一個陣列 $nums$,要找出從 $nums$ 之中任意取 3 個數字計算 XOR 的結果共有幾個,取的數字可以重複。由於答案只要不重複的計算結果數量,很適合用集合儲存計算結果。這題基本上就是硬算,大約分成以下的步驟:
  1. 將 $nums$ 轉成集合,移除重複的數字,存入 uni_nums。
  2. 由 uni_nums 任意取兩個數字計算 XOR,存入 uni_pairs。
  3. 由 uni_pairs 取一個數字,由 uni_nums 取一個數字,計算 XOR,存入 uni_triplets。
  4. 回傳 uni_triplets 的長度。


Python 程式碼


Runtime: 5873 ms, beats 64.81%. Memory: 19.72 MB, beats 22.22%.
class Solution:
    def uniqueXorTriplets(self, nums: List[int]) -> int:
        uni_nums = set(nums)  # 不重複的數字
        # 由提示2、3,任意選兩個數字計算 XOR
        uni_pairs = {x^y for x in uni_nums for y in uni_nums}
        # 取出 uni_pairs 之中一個數字與 uni_nums 之中一個數字計算 XOR
        uni_triplets = {p^z for p in uni_pairs for z in uni_nums}
        # 回傳答案
        return len(uni_triplets)

Runtime: 6679 ms, beats 61.11%. Memory: 19.70 MB, beats 46.30%.
class Solution:
    def uniqueXorTriplets(self, nums: List[int]) -> int:
        uni_nums = set(nums)  # 不重複的數字
        # 由提示2、3,任意選兩個數字計算 XOR
        uni_pairs = set()
        for y in uni_nums:
            for x in uni_nums:
                uni_pairs.add(x^y)
        # 取出 uni_pairs 之中一個數字與 uni_nums 之中一個數字計算 XOR
        uni_triplets = set()
        for p in uni_pairs:
            for z in uni_nums:
                uni_triplets.add(p^z)
        # 回傳答案
        return len(uni_triplets)


C++ 程式碼


Runtime: 1779 ms, beats 45.51%. Memory: 104.08 MB, beats 6.18%.
class Solution {
public:
    int uniqueXorTriplets(vector<int>& nums) {
        // 轉成集合,移除重複的數字
        unordered_set<int> uni_nums (nums.begin(), nums.end());
        // 由 uni_nums 任意取兩個數字計算 XOR
        unordered_set<int> uni_pairs;
        for(int x : uni_nums) {
            for(int y : uni_nums) {
                uni_pairs.insert(x^y);
            }
        }
        // 由 uni_pairs 取一個數字,由 uni_nums 取一個數字,計算 XOR
        unordered_set<int> uni_triplets;
        for(int p : uni_pairs) {
            for(int z : uni_nums) {
                uni_triplets.insert(p^z);
            }
        }
        return uni_triplets.size();
    }
};


沒有留言:

張貼留言