RainX_69

Interval Minimum Coverage (IMPORTANT)

Jan 17th, 2023 (edited)
77
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.05 KB | Source Code | 0 0
  1. https://www.lintcode.com/problem/1668/description?_from=cat
  2.  
  3. There are n intervals in number axis. Now we need to choose some points to make that there is at least one point in each interval.
  4.  
  5. Return the minimum number of chosen points.
  6.  
  7. 1 <= n <= 10^4
  8.  
  9. Example 1:
  10. Input: [(1,5), (4,8), (10,12)]
  11. Output: 2
  12. Explanation:
  13.   Choose two points: 5, 10
  14.   The first  interval [1, 5] contains 5
  15.   The second interval [4, 8] contains 5
  16.   The third  interval [10, 12] contains 10
  17.  
  18. Example 2:
  19. Input: [(1,5), (4,8), (5,12)]
  20. Output: 1
  21. Explanation: All intervals contain 5
  22.  
  23.  
  24. /**
  25.  * Definition of Interval:
  26.  * class Interval {
  27.  * public:
  28.  *     int start, end;
  29.  *     Interval(int start, int end) {
  30.  *         this->start = start;
  31.  *         this->end = end;
  32.  *     }
  33.  * }
  34.  */
  35.  
  36. ---------------------------------------------------------------------------------------------------------------------------------------
  37. CODE #1
  38.  
  39. class Solution {
  40. public:
  41.     static bool cmp(Interval &p, Interval &q){
  42.         if(p.end!=q.end){  
  43.             return p.end<q.end;
  44.         }
  45.         return p.start>q.start;
  46.     }
  47.      
  48.     int getAns(vector<Interval> &a) {
  49.         sort(a.begin(),a.end(),cmp);
  50.         int res=1;
  51.         int endPrev=a[0].end;
  52.         for(int i=1;i<a.size();i++){
  53.             if(a[i].start>endPrev){
  54.                 endPrev=a[i].end;
  55.                 res++;
  56.             }
  57.         }
  58.         return res;
  59.     }
  60. };
  61.  
  62. --------------------------------------------------------------------------------------------------------------------------------------
  63. CODE #2
  64.  
  65. class Solution {
  66. public:
  67.     int getAns(vector<Interval> &a) {
  68.         sort(a.begin(),a.end());
  69.         int res=1;
  70.         int eP=a[0].end;  //end previous point
  71.         for(int i=1;i<a.size();i++){
  72.             if(eP<a[i].start){
  73.                 res++;
  74.                 eP=a[i].end;
  75.             }
  76.             else{
  77.                 eP=min(eP,a[i].end);  // you wanna maintain the minimum eP so that prev guys have points within them
  78.             }
  79.         }
  80.         return res;
  81.     }
  82. };
Advertisement
Add Comment
Please, Sign In to add comment