class Solution {
public:
vector<string> findItinerary(vectorstring , string>> tickets) {
tickets_.clear();
routes_.clear();
for(const auto& tic: tickets) {
tickets_[tic.first].push_back(tic.second);
}
for(auto& tic:tickets_) {
auto& dests = tic.second;
std::sort(dests.begin(), dests.end());
}
const string stt="JFK";
schedule(stt);
return vector<string>(routes_.crbegin(), routes_.crend());
}
private:
unordered_map<string, deque<string>> tickets_;
vector<string> routes_;
void schedule(const string&stt_station) {
auto& visit = tickets_[stt_station];
while(!visit.empty()) {
string dest=visit.front();
visit.pop_front();
schedule(dest);
}
routes_.push_back(stt_station);
}
};
class Solution {
public:
int BFS(vector<vector<int>> forest, int ty, int tx, int cy, int cx) {
int h = forest.size();
int w = forest[0].size();
int step = 0;
queueint , int>> visited;
visited.push(make_pair(cy, cx));
int dirs[4][2] = {
{-1, 0}, {
0, 1}, {
1, 0}, {
0, -1}};
while(visited.size()) {
int tmp = visited.size();
for(int idx = 0; idx < tmp; idx++) {
auto tp = visited.front();
int tmp_y = tp.first;
int tmp_x = tp.second;
if(tmp_y == ty && tmp_x == tx) {
return step;
}
visited.pop();
forest[tmp_y][tmp_x] = 0;
for(int i = 0; i < 4; i++) {
int tmp_y_ = tmp_y+dirs[i][0];
int tmp_x_ = tmp_x+dirs[i][1];
if(tmp_y_ >= 0 && tmp_y_< h) {
if(tmp_x_>= 0 && tmp_x_< w) {
if(forest[tmp_y_][tmp_x_] > 0) {
visited.push(make_pair(tmp_y_, tmp_x_));
forest[tmp_y_][tmp_x_] = 0;
}
}
}
}
}
step++;
}
return INT_MAX;
}
int cutOffTree(vector<vector<int>>& forest) {
int ans = 0;
int h = forest.size();
if(!h) {
return ans;
}
int w = forest[0].size();
vectorint , int, int> > trees;
for(int idx1 = 0; idx1 < h; idx1++) {
for(int idx2 = 0; idx2 < w; idx2++) {
if(forest[idx1][idx2] > 1) {
trees.emplace_back(forest[idx1][idx2], idx1, idx2);
}
}
}
// cout << trees.size() << endl;
sort(trees.begin(), trees.end());
int len = trees.size();
int cx = 0, cy = 0;
for(int idx = 0; idx < len; idx++) {
int ty = get<1>(trees[idx]);
int tx = get<2>(trees[idx]);
int steps = BFS(forest, ty, tx, cy, cx);
// cout << steps << endl;
if(steps == INT_MAX) {
return -1;
}
ans += steps;
cy = ty;
cx = tx;
}
return ans;
}
};
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
if(grid.empty()) {
return 0;
}
rows = grid.size();
if(!rows) {
return 0;
}
cols = grid[0].size();
int num_iland = 0;
for(int i = 0; i < rows; i++) {
for(int j = 0; j < cols; j++) {
if(grid[i][j]=='1') {
dfs(grid, i, j);
num_iland++;
}
}
}
return num_iland;
}
private:
int rows;
int cols;
void dfs(vector<vector<char>>&grid, int row, int col) {
if(row < 0 || col < 0 || row >= rows || col >= cols) {
return;
}
if(grid[row][col]=='0') {
return;
}
grid[row][col]='0';
dfs(grid,row-1,col);
dfs(grid,row+1,col);
dfs(grid,row,col-1);
dfs(grid,row,col+1);
}
};
class Solution {
private:
void dfs(vector<vector<int>>&M, vector<int>&rec, int n, int idx) {
if(rec[idx]) {
return;
}
rec[idx]=1;
for(int i=0;iif(M[idx][i] && !rec[i]) {
dfs(M, rec, n, i);
}
}
}
public:
int findCircleNum(vector<vector<int>>& M) {
assert(!M.empty() && M.size()>0 && M.size()==M[0].size());
int n=M.size();
int ans=0;
vector<int> rec(n,0);
for(int i=0; iif(rec[i]) {
continue;
}
ans++;
dfs(M,rec,n,i);
}
return ans;
}
};
class Solution {
private:
void dfs(vector<vector<int>>&M, int n, int idx) {
if(!M[idx][idx]) {
return;
}
M[idx][idx]=0;
for(int i=0;iif(M[idx][i]) {
M[idx][i] = M[i][idx] = 0;
dfs(M, n, i);
}
}
}
public:
int findCircleNum(vector<vector<int>>& M) {
assert(!M.empty() && M.size()>0 && M.size()==M[0].size());
int n=M.size();
int ans=0;
for(int i=0; iif(!M[i][i]) {
continue;
}
ans++;
dfs(M,n,i);
}
return ans;
}
};
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(beginWord.size() != endWord.size() && beginWord.size() != 0) {
return 0;
}
unordered_set<string> words(wordList.begin(),wordList.end());
unordered_map<string,int> dict;
dict[beginWord]=-1;
queue<string> que;
que.push(beginWord);
int ans = 0;
int len = beginWord.size();
while(!que.empty()) {
int size = que.size();
while(size-- > 0) {
string cur_str = que.front();
que.pop();
if(cur_str==endWord) {
return ans+1;
}
int loc=dict[cur_str];
for(int idx=0;idxif(loc==idx){
continue;
}
string tmp=cur_str;
for(char a='a';a<='z';a++){
tmp[idx]=a;
if(words.find(tmp) != words.end()) {
que.push(tmp);
words.erase(tmp);
dict[tmp]=idx;
}
}
}
}
ans++;
}
return 0;
}
};
class Solution {
public:
int ladderLength(string beginWord, string endWord, vector<string>& wordList) {
if(beginWord.size() != endWord.size() && beginWord.size() != 0) {
return 0;
}
unordered_set<string> words(wordList.begin(),wordList.end());
if(words.find(endWord)==words.end()) {
return 0;
}
unordered_map<string,int> dict;
dict[beginWord]=-1;
dict[endWord]=-1;
unordered_set<string> que1;
unordered_set<string> que2;
que1.insert(beginWord);
que2.insert(endWord);
int ans = 0;
int len = beginWord.size();
while(!que1.empty() && !que2.empty()) {
ans++;
if(que1.size() > que2.size()) {
std::swap(que1,que2);
}
unordered_set<string> s;
for(string s1:que1) {
cout <" ";
for(int i=0;istring tmp=s1;
if(dict[tmp]==i){
continue;
}
for(char a='a';a<='z';a++){
tmp[i]=a;
if(que2.count(tmp)>0){
return ans+1;
}
if(words.find(tmp)!=words.end()){
s.insert(tmp);
dict[tmp]=i;
words.erase(tmp);
}
}
}
}
std::swap(s,que1);
}
return 0;
/*
"hit"
"cog"
["hot","dot","dog","lot","log"]
*/
}
};
class Solution {
private:
bool hasPath(int stt,int fin,unordered_map<int,vector<int>> &graph,unordered_set<int> &visited) {
if(stt==fin) {
return true;
}
visited.insert(stt);
int len=graph[stt].size();
for(int i=0;iint new_stt=graph[stt][i];
if(visited.find(new_stt)==visited.end()) {
bool res=hasPath(new_stt,fin,graph,visited);
if(res) {
return res;
}
}
}
return false;
}
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
unordered_map<int,vector<int>> graph;
for(auto& edge:edges) {
unordered_set<int> visited;
int u=edge[0];
int v=edge[1];
if(hasPath(u,v,graph,visited)) {
return edge;
}
graph[u].push_back(v);
graph[v].push_back(u);
}
return {};
}
};
class UnionFindSet {
public:
vector<int> parents_;
vector<int> ranks_;
UnionFindSet(int n) {
ranks_=vector<int>(n+1,0);
parents_=vector<int>(n+1,0);
for(int i=0;ibool Union(int u, int v) {
int pu=Find(u);
int pv=Find(v);
if(pu==pv) {
return false;
}
if(ranks_[pv]>ranks_[pu]){
parents_[pu]=pv;
}
else if(ranks_[pu]>ranks_[pv]){
parents_[pv]=pu;
}
else{
parents_[pv]=pu;
ranks_[pv]+=1;
}
return true;
}
int Find(int u){
if(u!=parents_[u]){
parents_[u]=Find(parents_[u]);
}
return parents_[u];
}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
UnionFindSet s(edges.size());
for(const auto& edge: edges) {
if(!s.Union(edge[0],edge[1])) {
return edge;
}
}
return {};
}
};
/*
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector subordinates;
};
*/
class Solution {
private:
int dfs(unordered_map<int, Employee*>& recs,int id){
int s=recs[id]->importance;
vector<int> sub=recs[id]->subordinates;
for(int i=0;ireturn s;
}
public:
int getImportance(vector employees, int id) {
unordered_map<int, Employee*> recs;
for(auto employee:employees) {
recs[employee->id]=employee;
}
return dfs(recs,id);
}
};
/*
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector subordinates;
};
*/
class Solution {
public:
int getImportance(vector employees, int id) {
unordered_map<int, Employee*> recs;
for(auto employee:employees){
recs.emplace(employee->id,employee);
}
queue<int> que;
que.push(id);
int s=0;
while(!que.empty()) {
int cur=que.front();
que.pop();
s+=recs[cur]->importance;
vector<int> sub=recs[cur]->subordinates;
for(int i=0;ireturn s;
}
};
class Solution {
private:
bool hasCycle(vector<int>&visited,vector<vector<int>>&gra,int idx){
if(visited[idx]==2){
return false;
}
if(visited[idx]==1){
return true;
}
visited[idx]=1;
for(int ele:gra[idx]){
if(hasCycle(visited,gra,ele))
{
return true;
}
}
visited[idx]=2;
return false;
}
public:
bool canFinish(int numCourses, vectorint , int>>& prerequisites) {
int len=prerequisites.size();
if(!len || !numCourses){
return true;
}
vector<vector<int>> sche(numCourses);
for(auto pre:prerequisites){
sche[pre.second].push_back(pre.first);
}
vector<int> visited(numCourses,0);
for(int i=0; iif(hasCycle(visited,sche,i))
{
return false;
}
}
return true;
}
};
class Solution {
private:
bool hasCycle(vector<vector<int>>& gra,vector<int>&v,vector<int>&ans,int i){
if(v[i]==1){
return true;
}
if(v[i]==2){
return false;
}
v[i]=1;
for(auto m:gra[i]){
if(hasCycle(gra,v,ans,m)){
return true;
}
}
v[i]=2;
ans.push_back(i);
return false;
}
public:
vector<int> findOrder(int numCourses, vectorint , int>>& prerequisites) {
int len=prerequisites.size();
if(!len && !numCourses){
return {};
}
vector<vector<int>> gra(numCourses);
for(auto pre:prerequisites){
gra[pre.second].push_back(pre.first);
}
vector<int>ans;
vector<int>v(numCourses,0);
for(int i=0;iif(hasCycle(gra,v,ans,i)){
return {};
}
}
std::reverse(ans.begin(),ans.end());
return ans;
}
};
Bellman-Ford:
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
int T=100*101;
vector<int> dis(N,T);
dis[K-1]=0;
for(int i=0;ifor(auto ele:times){
int u=ele[0]-1;
int v=ele[1]-1;
int w=ele[2];
dis[v]=min(dis[u]+w,dis[v]);
}
}
int max_time = *max_element(dis.begin(),dis.end());
return max_time==T?-1:max_time;
}
};
Floyd-Warshall:
class Solution {
public:
int networkDelayTime(vector<vector<int>>& times, int N, int K) {
vector<vector<int>> dis(N,vector<int>(N,-1));
for(auto time:times){
dis[time[0]-1][time[1]-1]=time[2];
}
for(int i=0;i0;
}
for(int k=0;kfor(int i=0;ifor(int j=0;jif(dis[i][k]>=0&&dis[k][j]>=0){
if(dis[i][j]<0 || dis[i][j]>dis[i][k]+dis[k][j])
dis[i][j]=dis[i][k]+dis[k][j];
}
}
}
}
int ans=INT_MIN;
for(int i=0;iif(dis[K-1][i]<0){
return -1;
}
ans=max(ans,dis[K-1][i]);
}
return ans;
}
};
class Solution {
public:
int coinChange(vector<int>& coins, int amount) {
int len=coins.size();
if(!len || amount<0){
return -1;
}
vector<int> tres(amount+1,INT_MAX);
tres[0]=0;
for(int i=0;iint val=coins[i];
for(int j=val;j<=amount;j++){
if(tres[j-val]!=INT_MAX) {
tres[j]=min(tres[j],tres[j-val]+1);
}
}
}
return tres[amount]==INT_MAX?-1:tres[amount];
}
};
class Solution {
private:
void dfs(vector<string>&ans,
vector<vector<char>>& board,
string digits,
string cur) {
if(digits.size()==cur.size()){
ans.push_back(cur);
return;
}
int len=digits[cur.size()]-'0';
for(char c:board[len]){
cur.push_back(c);
dfs(ans,board,digits,cur);
cur.pop_back();
}
}
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()){
return {};
}
vector<vector<char>> board(10);
board[0]={
' '};
board[1]={};
board[2]={
'a','b','c'};
board[3]={
'd','e','f'};
board[4]={
'g','h','i'};
board[5]={
'j','k','l'};
board[6]={
'm','n','o'};
board[7]={
'p','q','r','s'};
board[8]={
't','u','v'};
board[9]={
'w','x','y','z'};
vector<string> ans;
string cur="";
dfs(ans,board,digits,cur);
return ans;
}
};
class Solution {
public:
vector<string> letterCombinations(string digits) {
if(digits.empty()){
return {};
}
vector<vector<char>> board(10);
board[0]={
' '};
board[1]={};
board[2]={
'a','b','c'};
board[3]={
'd','e','f'};
board[4]={
'g','h','i'};
board[5]={
'j','k','l'};
board[6]={
'm','n','o'};
board[7]={
'p','q','r','s'};
board[8]={
't','u','v'};
board[9]={
'w','x','y','z'};
vector<string> ans{
""};
for(char c:digits){
int len=ans.size();
for(int i=0;ifor(char h:board[c-'0']) {
ans.push_back(ans[i]+h);
}
}
ans.erase(ans.begin(),ans.begin()+len);
}
return ans;
}
};
class Solution {
public:
void findComb(vector<vector<int>>&ans,
vector<int>&candidates,
int stt,
int target,
vector<int>&cur) {
if(target==0){
ans.push_back(cur);
return;
}
for(int i=stt;iif(targetreturn;
}
cur.push_back(candidates[i]);
findComb(ans,candidates,i,target-candidates[i],cur);
cur.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
int len=candidates.size();
if(!len || target<0){
return {};
}
sort(candidates.begin(),candidates.end());
vector<vector<int>>ans;
vector<int>cur;
findComb(ans,candidates,0,target,cur);
return ans;
}
};
347. Top K Frequent Elements
class Solution {
public:
vector<int> topKFrequent(vector<int>& nums, int k) {
int len=nums.size();
if(!len){
return {};
}
unordered_map<int,int>rec;
for(auto num:nums){
rec[num]++;
}
int max_fre=0;
for(auto num:rec){
max_fre=max(max_fre,num.second);
}
vector<int>ans;
vector<vector<int>>recs(max_fre+1);
for(auto r:rec){
recs[r.second].push_back(r.first);
}
for(int i=max_fre;i>=1;i--){
if(recs[i].size()>0){
ans.insert(ans.end(), recs[i].begin(),recs[i].end());
}
if(ans.size()>=k){
return ans;
}
}
return ans;
}
};
692. Top K Frequent Words
class Solution {
private:
typedef pair<string,int>Node;
typedef function<bool(const Node&, const Node&)>Compare;
public:
vector<string> topKFrequent(vector<string>& words, int k) {
unordered_map<string, int> count;
for(const string str:words) {
count[str]++;
}
Compare comparator = [](const Node& a, const Node& b) {
if(a.second == b.second){
return a.first < b.first;
}
return a.second>b.second;
};
priority_queuevector,Compare>q(comparator);
for(const auto &kv: count) {
q.push(kv);
if(q.size()>k) {
q.pop();
}
}
vector<string> ans;
while(!q.empty()) {
ans.push_back(q.top().first);
q.pop();
}
std::reverse(ans.begin(),ans.end());
return ans;
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
int len=words.size();
if(!len){
return {};
}
unordered_map<string,int> rec;
for(auto str:words){
rec[str]++;
}
assert(k>=1 && k<=rec.size());
int max_fre=0;
for(auto str:rec){
max_fre=max(max_fre,str.second);
}
vector<set<string>> fre2str(max_fre+1);
for(auto str:rec){
fre2str[str.second].insert(str.first);
}
vector<string> ans;
for(int fre=max_fre;fre>0;fre--){
if(fre2str[fre].size()>0){
int diff=min(k-ans.size(),fre2str[fre].size());
ans.insert(ans.end(),fre2str[fre].begin(),fre2str[fre].end());
}
if(ans.size()>=k){
break;;
}
}
while(ans.size()>k){
ans.pop_back();
}
return ans;
}
};
128. Longest Consecutive Sequence
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_map<int,int>rec;
int ans=0;
for(auto num:nums){
if(rec.find(num)!=rec.end()){
continue;
}
int l = rec.count(num-1)>0?rec[num-1]:0;
int r = rec.count(num+1)>0?rec[num+1]:0;
int t = l+r+1;
rec[num-l]=rec[num]=rec[num+r]=t;
ans=max(ans,rec[num]);
}
return ans;
}
};
class Solution {
public:
int longestConsecutive(vector<int>& nums) {
unordered_set<int>rec(nums.begin(),nums.end());
int ans=0;
for(auto num:nums){
cout << num << endl;
if(rec.find(num-1)!=rec.end()){
continue;
}
int count=0;
while(rec.find(num++)!=rec.end()){
count++;
}
ans=max(ans,count);
}
return ans;
}
};
409. Longest Palindrome
class Solution {
public:
int longestPalindrome(string s) {
vector<int> rec(128,0);
for(char c:s){
rec[c]++;
}
int ans=0;
int odd=0;
for(int i=0;i<128;i++){
ans+=(rec[i]>>1)<<1;
odd|=rec[i]&1;
}
return ans+odd;
}
};
class MyCalendar {
public:
MyCalendar() {
}
bool book(int start, int end) {
for(auto rec:recs){
if(max(start,rec.first)return false;
}
}
recs.push_back(make_pair(start,end));
return true;
}
private:
vectorint ,int>> recs;
};
/**
* Your MyCalendar object will be instantiated and called as such:
* MyCalendar obj = new MyCalendar();
* bool param_1 = obj.book(start,end);
*/
class MyCalendar {
public:
MyCalendar() {
}
bool book(int start, int end) {
auto it = recs.lower_bound(start);
if(it!=recs.end()&&it->firstreturn false;
}
if(it!=recs.begin()&&(--it)->second>start){
return false;
}
recs[start]=end;
return true;
}
private:
map<int,int> recs;
};
/**
* Your MyCalendar object will be instantiated and called as such:
* MyCalendar obj = new MyCalendar();
* bool param_1 = obj.book(start,end);
*/
class Solution {
public:
vector merge(vector & intervals) {
if(intervals.empty()){
return {};
}
std::sort(intervals.begin(),intervals.end(),
[](const Interval&a, const Interval& b){
return a.startvector ans;
for(const auto interval:intervals){
if(ans.empty() || interval.start>ans.back().end) {
ans.push_back(interval);
}
else {
ans.back().end=max(ans.back().end,interval.end);
}
}
return ans;
}
};
/**
* Definition for an interval.
* struct Interval {
* int start;
* int end;
* Interval() : start(0), end(0) {}
* Interval(int s, int e) : start(s), end(e) {}
* };
*/
class Solution {
public:
vector insert(vector & intervals, Interval newInterval) {
auto it=intervals.begin();
while(it!=intervals.end()&&newInterval.start>it->start){
++it;
}
intervals.insert(it,newInterval);
vector ans;
for(const auto interval: intervals){
if(ans.empty() || ans.back().endelse {
ans.back().end=max(ans.back().end,interval.end);
}
}
return ans;
}
};