fork download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. class Solution {
  6. public:
  7. vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
  8.  
  9. vector<int> result;
  10.  
  11. for (int i = 0; i < nums1.size(); i++) {
  12. for (int j = 0; j < nums2.size(); j++) {
  13.  
  14. if (nums1[i] == nums2[j]) {
  15.  
  16. bool exists = false;
  17. for (int k = 0; k < result.size(); k++) {
  18. if (result[k] == nums1[i]) {
  19. exists = true;
  20. break;
  21. }
  22. }
  23.  
  24. if (!exists) {
  25. result.push_back(nums1[i]);
  26. }
  27.  
  28. break; // stop checking nums2 once match is found
  29. }
  30. }
  31. }
  32.  
  33. return result;
  34. }
  35. };
  36.  
  37. int main() {
  38. Solution solution;
  39.  
  40. vector<int> nums1 = {1, 2, 2, 1};
  41. vector<int> nums2 = {2, 2};
  42.  
  43. vector<int> result = solution.intersection(nums1, nums2);
  44.  
  45. cout << "Intersection: ";
  46. for (int num : result) {
  47. cout << num << " ";
  48. }
  49. cout << endl;
  50.  
  51. return 0;
  52. }
  53.  
Success #stdin #stdout 0.01s 5276KB
stdin
Standard input is empty
stdout
Intersection: 2