無序容器

沒有順序的關聯容器

unordered_map

/* 
 * NeetCode
 * Two Integer Sum
 * LeetCode
 * 1. Two Sum
*/
class Solution {
public:
    vector<int> twoSum(vector<int>& nums, int target) {
        unordered_map<int,int> um;
        for(int i=0;i<nums.size();++i){
            if(um.find(nums[i]) != um.end()){
                return {um[nums[i]],i};
            }else{
                um[target - nums[i]] = i;
            }
        }
        return {};
    }
};

unordered_set

/*
 * NeetCode
 * Longest Consecutive Sequence
 * LeetCode
 * 128. Longest Consecutive Sequence
*/
class Solution {
public:
    int longestConsecutive(vector<int>& nums) {
        if (nums.empty()) return 0;
        unordered_set<int> numSet(nums.begin(), nums.end());
        int longestStreak = 0;

        // numSet.count(x) //數x有幾個 ==1相當於find
        for (int num : nums) {
            if (!numSet.count(num - 1)) { // 往下減一 沒有 代表是起點
                int currentNum = num;
                int currentStreak = 1;

                while (numSet.count(currentNum + 1)) { // 一直往上加1找連續數列
                    currentNum += 1;
                    currentStreak += 1;
                }

                longestStreak = max(longestStreak, currentStreak);
            }else{
                // 代表不是起點
            }
        }

        return longestStreak;
    }
};

Last updated

Was this helpful?