2019.1.1
Leetcode 23. Merge k Sorted Lists
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
struct cmp{
bool operator()(ListNode *a,ListNode *b){
return a->val > b->val;
}
};
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode* head = new ListNode(0);
ListNode* ret = head;
priority_queue<ListNode*,vector<ListNode*>,cmp> pq;
for(int i = 0;i < lists.size();i++){
if(lists[i] != NULL)pq.push(lists[i]);
}
while(!pq.empty()){
ListNode* t = pq.top();
pq.pop();
head->next = new ListNode(t->val);
head = head->next;
if(t->next != NULL){
pq.push(t->next);
}
}
return ret->next;
}
};
399.Evaluate Division
BFS解答
class Solution {
public:
double BFS(string s1,string s2,map<string,vector<pair<string,double>>>& graph,map<string,double>& dist){
queue<string> qu;
qu.push(s1);
double thistimes = dist[s1];
while(!qu.empty()){
string x = qu.front();
qu.pop();
for(int i = 0;i < graph[x].size();i++){
string neighbour = graph[x][i].first;
double times = graph[x][i].second;
if(dist[neighbour] == 0.0){
qu.push(neighbour);
dist[neighbour] = dist[x] * times;
if(neighbour == s2)return dist[s2];
}
}
}
return -1.0;
}
vector<double> calcEquation(vector<pair<string, string>> equations, vector<double>& values, vector<pair<string, string>> queries) {
vector<double> res;
map<string,vector<pair<string,double>>> graph;
for(int i = 0;i < equations.size();i++){
string s1 = equations[i].first;
string s2 = equations[i].second;
double times = values[i];
graph[s2].push_back(make_pair(s1,1.0/times));
graph[s1].push_back(make_pair(s2,times));
}
for(int i = 0;i < queries.size();i++){
string s1 = queries[i].first;
string s2 = queries[i].second;
if(graph[s1].size() == 0 || graph[s2].size() == 0){
res.push_back(-1.0);
continue;
//not exist
}else if(s1 == s2){
res.push_back(1.0);
continue;
//the same && both exist
}
map<string,double> dist;
dist.clear();
dist[s1] = 1.0;
double ans = BFS(s1,s2,graph,dist);
res.push_back(ans);
}
return res;
}
};