iT邦幫忙

2026 iThome 鐵人賽

DAY 7
0
Software Development

30天刷完leetcoode75系列 第 7 篇

C++ 演算法練習 Day7|724, 2215, 1207題解與思路分享

  • 分享至 

  • xImage
  •  

https://ithelp.ithome.com.tw/upload/images/20260921/20184265ScvtYtpLlL.png

題目解析:在一個整數陣列中找出中心索引(pivot index),也就是該位置左邊所有數字的總和要等於右邊所有數字的總和,如果找不到就回傳 -1
解題思路:先設一個前綴和陣列 v 把每一項累加進去,然後丟進迴圈開始跑,分別判斷最左邊、最右邊以及中間的情況,只要左邊總和等於右邊總和就直接回傳該位置 i,跑完都沒找到就回傳 -1

class Solution {
public:
    int pivotIndex(vector<int>& nums) {
        vector<int> v;
        v.push_back(nums[0]);
        for(int i=1; i<nums.size(); i++){
            v.push_back(nums[i] + v.back());
        }

        for(int i=0; i<v.size(); i++){
            if(i == 0 && v[v.size()-1] - v[i] == 0) return 0;
            else if(i == v.size()-1 && v[v.size()-2] == 0) return v.size()-1;
            else if(i != 0 && i != v.size()-1 && v[v.size()-1] - v[i] == v[i-1]) return i;
        }


        return -1;
    }
};

https://ithelp.ithome.com.tw/upload/images/20260921/20184265qNVCJjXOEF.png

題目解析:給定兩個整數陣列 nums1 與 nums2,找出只出現在 nums1 但沒在 nums2 的相異數字,以及只出現在 nums2 但沒在 nums1 的相異數字,最後將這兩組數字分別打包成一個二維陣列回傳
解題思路:先將兩個陣列分別丟進 unordered_set 去重並方便快速查找,接著開一個大小為 2 的二維陣列 v,然後丟進迴圈開始跑,分別檢查 s1 中的元素是否有在 s2 出現過、s2 中的元素是否有在 s1 出現過,沒出現的就 push_back 進去,最後回傳 v

class Solution {
public:
    vector<vector<int>> findDifference(vector<int>& nums1, vector<int>& nums2) {
        unordered_set<int> s1(nums1.begin(), nums1.end());
        unordered_set<int> s2(nums2.begin(), nums2.end());
        vector<vector<int>> v(2);

        for(int x : s1) if(!s2.count(x)) v[0].push_back(x);
        for(int x : s2) if(!s1.count(x)) v[1].push_back(x);

        return v;
    }
};

https://ithelp.ithome.com.tw/upload/images/20260921/20184265V0l4OuL8L3.png

題目解析:給定一個整數陣列 arr,判斷陣列中每個數值出現的次數是否都是獨一無二的,如果出現次數都沒有重複就回傳 true,否則回傳 false
解題思路:先設一個 map v 記錄每個數字出現的次數,接著開一個 set v1,然後丟進迴圈開始跑,檢查目前這個次數是否已經在 set 裡面出現過,如果有重複就回傳 0,沒有就 insert 進去,全部檢查完都沒重複就回傳 1

class Solution {
public:
    bool uniqueOccurrences(vector<int>& arr) {
        map<int, int> v;
        set<int> v1;
        for(auto it : arr){
            v[it]++;
        }

        for(auto it : v){
            if(v1.count(it.second)) return 0;
            v1.insert(it.second);
        }

        return 1;
    }
};

上一篇
C++ 演算法練習 Day6|1004, 1493, 1732題解與思路分享
下一篇
C++ 演算法練習 Day8|1657 ,2352 ,2390題解與思路分享
系列文
30天刷完leetcoode75 共 11 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言