Showing posts with label minimum heap. Show all posts
Showing posts with label minimum heap. Show all posts

Sunday, October 9, 2016

407. Trapping Rain Water II

I don't have any clue to solve the problem. I have to follow the top rated solution. The idea behind is
(1) Use minimum heap to store the height for most outer boarder and scan from the lowest height.
(2) For the top height in the heap (h1), we need to record the lowest height (it's the maxH in the code). (Why? Because it is the lowest height in the most out boundary, we expect it to grow only. If there is any height lower than current lowest height, it has trapped water.) If it has neighbor with lower height (h2), then the neighbor must be able to hold water (maxH - h2). Why? Because at this time the boundary has been updated and maxH is the lowest height so far, please see step (3).
(3) Mark the neighbor as visited and push it to the heap. Since the neighbor has been visited, the boundary is updated.
(4) repeat (2) - (3) until heap becomes empty.

1:  class Solution {  
2:  public:  
3:    int trapRainWater(vector<vector<int>>& heightMap) {  
4:      if (heightMap.empty()) return 0;  
5:      int rows = heightMap.size(), cols = heightMap[0].size();  
6:      priority_queue<pair<int,int>,vector<pair<int,int>>,greater<pair<int,int>>> q;  
7:      vector<vector<bool>> visited(rows, vector<bool>(cols, false));  
8:      for (int i = 0; i < rows; i++) {  
9:        for (int j = 0; j < cols; j++) {  
10:          if (i == 0 || i == rows-1 || j == 0 || j == cols-1) {  
11:            q.push(make_pair(heightMap[i][j], i*cols+j));  
12:            visited[i][j] = true;  
13:          }  
14:        }  
15:      }  
16:      vector<pair<int,int>> dir = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};  
17:      int res = 0, maxH = INT_MIN;  
18:      while (!q.empty()) {  
19:        int height = q.top().first;  
20:        int i = q.top().second / cols, j = q.top().second % cols;  
21:        q.pop();  
22:        maxH = max(maxH, height);  
23:        for (int d = 0; d < dir.size(); d++) {  
24:          int ii = i + dir[d].first;  
25:          int jj = j + dir[d].second;  
26:          if (ii < 0 || jj < 0 || ii == rows || jj == cols || visited[ii][jj]) continue;  
27:          visited[ii][jj] = true;  
28:          if (heightMap[ii][jj] < maxH) res += maxH - heightMap[ii][jj];  
29:          q.push(make_pair(heightMap[ii][jj], ii*cols+jj));  
30:        }  
31:      }  
32:      return res;  
33:    }  
34:  };  

Saturday, August 13, 2016

347. Top K Frequent Elements

Whenever the problem asks for top k numbers, it's highly likely to consider heap. This is a typical heap problem plus hash map. The hash map is used to count the frequency for each number the (key, value) pair is (number, frequency). After completing the hash map build, we build the minimal heap according the frequency. The node in heap is also a pair but this time it is (frequency, number) pair. Since we know that we only need to keep k numbers in the heap, so when the heap size is larger than k we pop out the top number. Finally, we dump all the numbers in the heap to the vector.

1:  class Solution {  
2:  public:  
3:    vector<int> topKFrequent(vector<int>& nums, int k) {  
4:      unordered_map<int, int> mp;  
5:      for (int i = 0; i < nums.size(); i++) {  
6:        mp[nums[i]]++;  
7:      }  
8:      priority_queue<pair<int, int>, vector<pair<int,int>>, greater<pair<int,int>>> minHeap;  
9:      for (auto p : mp) {  
10:        minHeap.push(make_pair(p.second, p.first));  
11:        if (minHeap.size() > k) {  
12:          minHeap.pop();  
13:        }  
14:      }  
15:      vector<int> res(k, 0);  
16:      for (int i = k-1; i >= 0; i--) {  
17:        res[i] = minHeap.top().second;  
18:        minHeap.pop();  
19:      }  
20:      return res;  
21:    }  
22:  };  

Monday, August 8, 2016

378. Kth Smallest Element in a Sorted Matrix

I tried a way of moving two pointers from top left/bottom right corner but found it is not able to solve the problem. Then I followed the top rated solution to solve the problem by minimal heap.
The idea is to push the numbers of first row into the heap. The heap is ordered by the value of numbers. Once we pop out the top number, we need to find the next possible number. It will be  the number on next row in the same column with the popped number. Therefore, we need to append the position information to the number. So the code is as following:

1:  class Solution {  
2:  public:  
3:    int kthSmallest(vector<vector<int>>& matrix, int k) {  
4:      priority_queue<pair<int,pair<int, int>>, vector<pair<int,pair<int, int>>>, greater<pair<int, pair<int, int>>>> minHeap;  
5:      int n = matrix.size();  
6:      for (int j = 0; j < n; j++) {  
7:        minHeap.push(make_pair(matrix[0][j], make_pair(0, j)));  
8:      }  
9:      int res = 0;  
10:      while (k) {  
11:        int i = minHeap.top().second.first;  
12:        int j = minHeap.top().second.second;  
13:        res = matrix[i++][j];  
14:        minHeap.pop();  
15:        if (i < n ) minHeap.push(make_pair(matrix[i][j], make_pair(i, j)));  
16:        k--;  
17:      }  
18:      return res;  
19:    }  
20:  };  

Friday, July 15, 2016

253. Meeting Rooms II

The idea is to sort the intervals first according to the start time. Then set up a minimum heap according the end time. So when we take the top interval of the heap, we'll get the meeting that ends up earliest. If the new interval starts behind the top meeting, we can reuse the meeting room the top one was using so we don't have to order a new meeting room. All we need to do is to update the end time of this room to eh new interval's end time. Why we don't need to care the gap between the last meeting and the new meeting? Because the intervals are sorted by start time, so it's guaranteed that no new meeting will insert into the gap.

1:  /**  
2:   * Definition for an interval.  
3:   * struct Interval {  
4:   *   int start;  
5:   *   int end;  
6:   *   Interval() : start(0), end(0) {}  
7:   *   Interval(int s, int e) : start(s), end(e) {}  
8:   * };  
9:   */  
10:  struct compare {  
11:    bool operator() (const Interval& a, const Interval& b){  
12:      return a.end > b.end;  
13:    }  
14:  };  
15:  class Solution {  
16:  public:  
17:    int minMeetingRooms(vector<Interval>& intervals) {  
18:      if (intervals.size() == 0) return 0;  
19:      // sort according to the start time.  
20:      sort(intervals.begin(), intervals.end(), [](Interval a, Interval b) { return a.start < b.start; });  
21:      priority_queue<Interval, vector<Interval>, compare> min_heap;  
22:      min_heap.push(intervals[0]);  
23:      for (int i = 1; i < intervals.size(); i++) {  
24:        Interval interval = min_heap.top();  
25:        min_heap.pop();  
26:        if (interval.end > intervals[i].start) {  
27:          min_heap.push(intervals[i]);  
28:        } else {  
29:          interval.end = intervals[i].end;  
30:        }  
31:        min_heap.push(interval);  
32:      }  
33:      return min_heap.size();  
34:    }  
35:  };  

When I revisited this problem, I had a more concise solution with the same idea behind. I don't have to store the intervals in the min heap but the ending time.

1:  /**  
2:   * Definition for an interval.  
3:   * struct Interval {  
4:   *   int start;  
5:   *   int end;  
6:   *   Interval() : start(0), end(0) {}  
7:   *   Interval(int s, int e) : start(s), end(e) {}  
8:   * };  
9:   */  
10:  class Solution {  
11:  public:  
12:    int minMeetingRooms(vector<Interval>& intervals) {  
13:      if (intervals.size() < 2) return intervals.size();  
14:      sort(intervals.begin(), intervals.end(), [](Interval a, Interval b){ return a.start < b.start; });  
15:      priority_queue<int, vector<int>, greater<int>> q;  
16:      for (int i = 0; i < intervals.size(); i++) {  
17:        if (q.empty() || intervals[i].start < q.top()) q.push(intervals[i].end);  
18:        else {  
19:          int t = q.top();  
20:          q.pop();  
21:          t = intervals[i].end;  
22:          q.push(t);  
23:        }  
24:      }  
25:      return q.size();  
26:    }  
27:  };  

Monday, July 4, 2016

355. Design Twitter

We need to use hash map to store the mapping between one follower and followees. Each follower has multiple followees so we need set to store all followees for one follower. For tweets, we need to add timeline for each tweet such that we know which is the latest one. When popping out top latest 10 tweets of a user, all we need to do is:
(1). Get all friends of this user.
(2). Iterate the friend list.
(3). For each friend, iterate his/her tweets list.
(4). We use a priority queue with least recent tweets on top to keep the 10 most recent tweets. If the queue is not full, we keep pushing. If the queue is full, we check the top tweet is less recent than the incoming tweet. If so, push the incoming tweet into the queue. If not, we stop scanning this friend's tweets because his/her tweets are ordered from most recent to least recent. If the queue size is large than 10, we pop out the top.
(5). At the end, we output tweets in the queue in reverse order.

Also, one important point that can be easy to miss is that user herself need to follow herself! Why? Because she must be able to see her own tweets. Also when doing unfollow, we need to make sure that user mustn't unfollow herself.

Note, line 14 is an optimization for getNewsFeed(), so that line 22 can detect early break.

1:  class Twitter {  
2:  private:  
3:    unordered_map<int, unordered_set<int>> friends;  
4:    unordered_map<int, vector<pair<int, int>>> tweets;  
5:    int time;  
6:  public:  
7:    /** Initialize your data structure here. */  
8:    Twitter() {  
9:      time = 0;  
10:    }  
11:    /** Compose a new tweet. */  
12:    void postTweet(int userId, int tweetId) {  
13:      follow(userId, userId);  
14:      tweets[userId].insert(tweets[userId].begin(), pair<int, int>(++time, tweetId));  
15:    }  
16:    /** Retrieve the 10 most recent tweet ids in the user's news feed. Each item in the news feed must be posted by users who the user followed or by the user herself. Tweets must be ordered from most recent to least recent. */  
17:    vector<int> getNewsFeed(int userId) {  
18:      vector<int> res;  
19:      priority_queue<pair<int, int>, vector<pair<int, int>>, std::greater<pair<int, int>>> que;  
20:      for (int f : friends[userId]) {  
21:        for (pair<int, int> t : tweets[f]) {  
22:          if (que.size() == 10 && que.top().first > t.first) break;  
23:          que.push(t);  
24:          if (que.size() > 10) que.pop();  
25:        }  
26:      }  
27:      while (!que.empty()) {  
28:        res.push_back(que.top().second);  
29:        que.pop();  
30:      }  
31:      reverse(res.begin(), res.end());  
32:      return res;  
33:    }  
34:    /** Follower follows a followee. If the operation is invalid, it should be a no-op. */  
35:    void follow(int followerId, int followeeId) {  
36:      friends[followerId].insert(followeeId);  
37:    }  
38:    /** Follower unfollows a followee. If the operation is invalid, it should be a no-op. */  
39:    void unfollow(int followerId, int followeeId) {  
40:      if (followerId != followeeId) {  
41:        friends[followerId].erase(followeeId);  
42:      }  
43:    }  
44:  };  
45:  /**  
46:   * Your Twitter object will be instantiated and called as such:  
47:   * Twitter obj = new Twitter();  
48:   * obj.postTweet(userId,tweetId);  
49:   * vector<int> param_2 = obj.getNewsFeed(userId);  
50:   * obj.follow(followerId,followeeId);  
51:   * obj.unfollow(followerId,followeeId);  
52:   */