Advertisement
Guest User

Untitled

a guest
Sep 21st, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. class Solution {
  2. public:
  3. vector<int> advantageCount(vector<int>& A, vector<int>& B) {
  4. vector<int> res (A.size(), -1);
  5. vector<pair<int, int>> As;
  6. vector<pair<int, int>> Bs;
  7.  
  8. //Store as (index, value) pair
  9. for (int i=0; i<A.size(); i++)
  10. {
  11. As.push_back(make_pair(i, A[i]));
  12. }
  13.  
  14. for (int i=0; i<B.size(); i++)
  15. {
  16. Bs.push_back(make_pair(i, B[i]));
  17. }
  18.  
  19. //Sort by value using custom sort operator for pairs
  20. sort (As.begin(), As.end(), Solution());
  21. sort (Bs.begin(), Bs.end(), Solution());
  22.  
  23. int i = 0, j = 0;
  24. for (; i<As.size(); )
  25. {
  26. if (As[i].second>Bs[j].second)
  27. {
  28. res[Bs[j].first] = As[i].second; //Insert in to the right position in result
  29. As[i].first = As.size(); //Mark invalid
  30. i++;j++;
  31. }
  32. else
  33. {
  34. i++;
  35. }
  36. }
  37.  
  38. //Insert remaining values from A into the result
  39. i = 0; j = 0;
  40. for (; i<res.size(); )
  41. {
  42. if (res[i] == -1)
  43. {
  44. while(j<As.size() && As[j].first == As.size())
  45. {
  46. j++;
  47. }
  48. if (j<As.size())
  49. res[i] = As[j].second;
  50. j++; //Don't forget this
  51. }
  52. i++;
  53.  
  54. }
  55.  
  56. return res;
  57. }
  58.  
  59. bool operator() (pair<int,int> a, pair<int,int> b)
  60. {
  61. return a.second<b.second;
  62. }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement