fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. vector<int> twoSum(vector<int>& nums, int target) {
  4. map<int, int> indexMap;
  5. vector<int> result;
  6. int n = nums.size();
  7. for(int i = 0; i < n; i++){
  8. if(indexMap.find(nums[i] - target) != indexMap.end()){
  9. result.push_back(indexMap[nums[i]]);
  10. result.push_back(i);
  11. } else{
  12. indexMap[nums[i]] = i;
  13. }
  14. }
  15. return result;
  16. }
  17. int main() {
  18. map<int, int> indexMap;
  19. vector<int> result, nums(4);
  20. nums[0] = 3; nums[1] = 2; nums[2] = 6; nums[3] = 5;
  21. int target = 5;
  22. int n = nums.size();
  23. for(int i = 0; i < n; i++){
  24. if(indexMap.find(target - nums[i]) != indexMap.end()){
  25. result.push_back(indexMap[nums[i]]);
  26. result.push_back(i);
  27. cout << indexMap[target - nums[i]] << " " << i << endl;
  28. break;
  29. } else{
  30. indexMap[nums[i]] = i;
  31. }
  32. }
  33. return 0;
  34. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
0 1