meyr543
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    2
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # Leetcode刷題學習筆記--Set/Multiset ## Introduction ref : [Difference Between set, multiset, unordered_set, unordered_multiset in C++](https://www.geeksforgeeks.org/difference-between-set-multiset-unordered_set-unordered_multiset-in-cpp/) | | 排序 | 允許重複資料 | 用途 | | ------------------ | ------------------ | ------------ | --- | | set | :heavy_check_mark: | | 排序不重複資料 | | unordered_set | || 檢查資料單一性</br>當成hash table使用 | | multiset | :heavy_check_mark: | :heavy_check_mark: | 排序重複資料 | | unordered_multiset | |:heavy_check_mark:| | + set/multiset只能存放一個資料,不像map可以存key-value pair。 + ==數字放入set會依小到大排序,字串放入set會依字典序排序。== ## Time Complexity ref : [Data Structures: MULTI_SET vs SET vs UNORDERED_SET](https://medium.com/geekculture/data-structures-multi-set-vs-set-vs-unordered-set-bcc4f6609ac9) | Container | insert() | erase() | find() | Implement| | ------------------ | -------- | ------- | ------ | --- | | set | $O(logN)$| $O(logN)$|$O(logN)$|Binary Search Tree| | unordered_set | $O(1)$ | $O(1)$ |$O(1)$ |Hash Table| | multiset | $O(logN)$| $O(logN)$|$O(logN)$|Red Black Tree| | unordered_multiset | $O(1)$ | $O(1)$ |$O(1)$ |Hash Table| ## Code snippet ### 檢查資料是否重複 把每筆資料轉換成單一的識別碼,從而檢查是否重複。可以使用set。 ```cpp= vector<int> nums; unordered_set<int> s(nums.begin(), nums.end()); // check if num has alreay existed in set if(s.count(num)) {...} ``` ### 只能insert和erase不能修改資料 ```cpp= unordered_set<int> s; s.insert(1); s.insert(2); s.erase(1); ``` + multiset/unordered_multiset 的資料刪除 因為multiset和unordered_multiset可以允許重複的資料, 使用erase或刪除相同的資料,所以必須使用find。 ```cpp= multiset<int> ms; ms.erase(ms.find(num)); ``` ### 如果是插入到set或是multiset,可以知道插入的位置。 視情況如果想知道insert的位置。 ```cpp= set<int> s; int nums = 5; auto it = s.insert(nums); // get the iterator of inserted number int idx = it - s.begin(); ``` ### Traversal the set 使用iterator來存取所有的item,或是使用for loop來存取所有的資料。 ref : [Different ways to iterate over a set in C++](https://www.geeksforgeeks.org/different-ways-to-iterate-over-a-set-in-c/) ```cpp= set<int> s; // iterator為指向set中的element,可視為pointer,必須使用*來取值。 for(auto it = s.begin(); it != s.end(); ++it) cout << *it << endl; // for loop 直接就會拿到element的reference for(auto& n : s) cout << n << endl; // 必須使用const來定義輸入argument,因為set內的element也是const, // 所以只能刪除不能修改。 // (start iterator, end iterator, funcion pointer) auto print = [&](const int& x) { cout << x << endl; }; for_each(s.begin(), s.end(), print); for_each(s,begin(), s.end(), [&](const int& x){ cout << x << endl; }); ``` ### 改變Set排列順序 + 預設Set排列,integer為從小到大,string為字典序排列。 + 但是有些情況想要有integer從大到小的排列。 1. 使用iterator ```cpp= for(auto it = s.rbegin(); it != r.end(); ++it) { cout << *it << endl; } ``` 2. 使用compare ```cpp= set<int, less<int>> s; // 從小到大 set<int, greater<int>> s; //從大到小 ``` 3. 反轉key ```cpp= vector<int> nums; set<int> s; for(auto& n : nums) s.insert(-1 * n); ``` ### Sets of pairs in C++ ref : [Sets of pairs in C++](https://www.geeksforgeeks.org/sets-of-pairs-in-c/) 在Set中存放pairs。則會先依pairs first element排序,如果first element一樣就會用second element排序。 ### Custom Comparator ref : [Using custom std::set comparator](https://stackoverflow.com/questions/2620862/using-custom-stdset-comparator) + Modern C++11 Solution ```cpp= auto cmp = [](int a, int b) { return a < b; // 從小到大 }; set<int, decltype(cmp)> s(cmp); ``` + function pointer ```cpp= bool cmp(int a, int b) { return a < b; } set<int, decltype(&cmp)> s(&cmp); ``` ### [36. Valid Sudoku(Medium)](https://leetcode.com/problems/valid-sudoku/) 找出行,列,每個block是否有數字重複。 ```cpp= class Solution { public: bool isValidSudoku(vector<vector<char>>& board) { unordered_set<string> s; string t1, t2, t3; for(int i = 0; i < 9; ++i) { for(int j = 0; j < 9; ++j) { if(board[i][j]=='.') continue; t1 = to_string(i) + "r" + board[i][j]; t2 = to_string(j) + "c" + board[i][j]; t3 = to_string(i / 3) + to_string(j / 3) + "e" + board[i][j]; if(s.count(t1) || s.count(t2) || s.count(t3)) return false; else { s.insert(t1); s.insert(t2); s.insert(t3); } } } return true; } }; ``` ### [929. Unique Email Addresses(Easy)](https://leetcode.com/problems/unique-email-addresses/) 找出不同的email address,判斷規則參考題目。 > 使用unordered_set來過濾是否有重複的email address。**unordered_set<string> valid_mails;** > 把email分成local name和domain name。對localname進行處理。把"+"以後的字串都刪除掉,然後把"."都拿掉。 完整程式碼如下: ```cpp= int numUniqueEmails(vector<string>& emails) { unordered_set<string> valid_mails; for(auto& mail : emails) { int pos = mail.find("@"); string localname = mail.substr(0, pos); string domainname = mail.substr(pos + 1); int p = localname.find("+"); string newname = localname.substr(0, p); newname.erase(std::remove(newname.begin(), newname.end(), '.'), newname.end()); valid_mails.insert(newname + "@" + domainname); } return valid_mails.size(); } ``` ### [220. Contains Duplicate III](https://leetcode.com/problems/contains-duplicate-iii/) 給你一個vector<int> nums, 找出index差小於等於k,且數字差小於等於t。 $abs(num[i] - nums[j]) <= t$ 且 $abs(i - j) <= k$。 > 1. 因為限制index差在k之內,所以使用slinding window,新增一個數nums[i]就刪除nums[i - k - 1] > 2. 使用multiset來記錄數字,因為數字可能重複。 > 3. 因為題目是要差值小於t,所以insert之後的數字只需要跟前後去比較。 > 4. **刪除的時候必須使用 s.earse(s.find(val)); 避免刪除全部相同的key。**,因為可能會遇到windows中好幾個相同的數值。 ```cpp= bool containsNearbyAlmostDuplicate(vector<int>& nums, int k, int t) { multiset<long> s; for(int i = 0; i < nums.size(); ++i) { // 使用find之後再erase避免刪除重複的key if(i - k - 1 >= 0) s.erase(s.find(nums[i - k - 1])); // O(logK + logK) // insert之後取得在multiset之中的位置。 auto it = s.insert(nums[i]); // O(logK) if(it != s.begin() && it - *prev(it) <= t) return true; if(next(it) != s.end() && *next(it) - *it <= t) return true; // time : O(N*3*logK) = O(NlogK), // K : size of slinding window // space : O(K) } return false; } ``` ###### tags: `leetcode` `刷題`

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully