Sunday, July 9, 2017

[c++] Leetcode

[Type]

[useful tools]

Hash

  • map (stl): map<string, string> map;
  • map.insert(pair<string, string>("yeah", "wow")): key"yeah" is mapped to value"wow"
    map["yeah"] = "wow"
  • map.find("yeah"): return the pointer pointing to slot with key "yeah"
  • map.find("yeah")->second: value of the slot with key "yeah"
  • REF: http://mropengate.blogspot.tw/2015/12/cc-map-stl.html
  • set (stl): set<string> set; // only key only, no key-value pair
  •   std::set<int> myset;
      std::set<int>::iterator itlow,itup;
    
      for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90
    
      itlow=myset.lower_bound (30);                //       ^
      itup=myset.upper_bound (60);                 //                   ^
    
      myset.erase(itlow,itup);                     // 10 20 70 80 90

String Operating

  • min(a, b): return smaller one
  • max(a, b): return larger one
  • reverse(s.begin(), s.end): void, reverse string s
  • a.compare(b): return 0 if a==b, 1 if a!=b
  • a.substr(begin, length): return a[begin:begin+length]
  • a.erase(a.begin(),a.end()) == a.clear() : clear all content
  • istringstream fin: fin>>word, or get line(fin, word, delimiter) 

Vector Operating

  • std::vector<int> v { 34,23 };
    // or
    // std::vector<int> v = { 34,23 };
  • push_back(a): void
  • pop_back(a): void
  • vector<T>::iterator: the pointer points to the vector
  • vector.begin(): return the pointer points to the first element
  • vector.end(): return the pointer points to last+1 position
  • vector.front(): return the value of first element
  • vector.back(): return the value of last element
  • vector.empty(): return boolean
  • vector.insert(a.begin(), value): insert value at a.begin(), return void
  • vector.insert(a.end(), b.begin(), b.end()): append b after a, return void
  • vector.erase(a.begin()+pos): erase the item of the pos
  • reverse(s.begin(), s.end): void, reverse vector s
  • std::random_shuffle(s.begin(), s.end()): void, inlace shuffling

DFS

BFS

  • queue<template> q
  • q.push(): push back
  • q.pop(): pop front
  • q.back(): return last value
  • q.front(): return first value

Quick Sort

Binary Sort 

Useful Tips

  • for(auto e: <iterable class>) //<iterable class>-> list, vector, map, set...etc
    traverse through the whole class
  • sort(<iterable class>.begin(), <iterable class>.end()) : void, directly sort inline        vector<string> test;
    test.push_back("ab");
    test.push_back("ac");
    test.push_back("aa");
    sort(test.begin(), test.end());
    test-> aa, ab, ac (sorted)
  • INT: 4 bytes/2 = 16 bits
  • INT_MAX: 2^15 - 1 = 32767
  • INT_MIN: -2^15 + 1 = -32767
  • pow(a, b): return a to the power of a

Algorithm by self-thinking

Dynamic Programming

Algorithm

Conversion

  • isdigit(int c): check whether character c is decimal digit or not. 

REF

No comments:

Post a Comment