day6 HashTable | 242 349 202 1

STL Set/Map

ContainerImplemented byOrderDuplicatableModifiableO(find)Insertion/Deletion
set / mapRed Black TreeOrderedNoNoO(logn)O(logn)
multiset / multimapRed Black TreeOrderedYesNoO(logn)O(logn)
unordered_set / unordered_mapHash TableUnorderdNoNoO(1)O(1)

242.Valid Anagram

Limited possiblities(26 character) => Use array int[]

  1. Counting numbers of elements for one words, and minusing the counts down when iterating characters of another word
  2. If any of the counters != 0, returns false

349.Intersection of Two Arrays

Limited possiblities(1 <= num <= 1000) => Use array
Only requiring the intersected numbers, not with the counters => bool[]

  1. Marking apperance of numbers as true bucket[num] = true from the first vector
  2. Iterating the second vector, insert the num in the results if bool[num] is true, and mark the flag as false bucket[num] = false to prevent multi insertion

202.Happy Number

  1. Happy number will end up to 1
  2. Unhappy number will go into a loop

=> Slow And Fast Pointers

bool isHappy(int n) 
{
    int slow = n, fast = n;
    do
    {
        fast = bitSquareSum(fast);
        fast = bitSquareSum(fast);
        slow = bitSquareSum(slow);
        if(slow == 1)
            return true;
    }while(slow!=fast);
    
    return false;
}

1. Two Sum

The Range of number is too large => Using unordered_map as bucket

unordered_map<int, int> bucket; // num -> index
for(int i = 0; i < nums.size(); ++i)
{
    if(auto n =bucket.find(target - nums[i]); n != bucket.end())
        return vector<int>{i, n->second};
    bucket.emplace(nums[i], i);
}
return vector<int>();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值