fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. vector<int> twoS(vector<int>& nums, int target) {
  5. unordered_map<int,int>umap;
  6. vector<int>ans;
  7. for(int i =0; i<nums.size(); i++) {
  8. int comp = target - nums[i];
  9.  
  10. if(umap.find(comp) != umap.end()) {
  11. ans.push_back(umap[comp]);
  12. ans.push_back(i);
  13. return ans;
  14. }
  15.  
  16. umap[nums[i]] = i;
  17. }
  18. // return empty
  19. return ans;
  20. }
  21.  
  22. /*
  23. Example 2:
  24. Input: nums = [3,3],
  25. target = 6
  26. Output: [0,1]
  27. */
  28.  
  29. int main() {
  30. vector<int>nums = {3,3};
  31. int target = 6;
  32. vector<int>res = twoS(nums, target);
  33. cout<< res[0]<<" "<<res[1]<<endl;
  34. return 0;
  35. }
Success #stdin #stdout 0.01s 5304KB
stdin
Standard input is empty
stdout
0 1