for (int i = 0; i < nums.size(); i++) { int looking = target - nums[i]; if (hash_map.find(looking) != hash_map.end()) { return {i, hash_map.at(looking)}; }
// add current num into map hash_map[nums[i]] = i; }
classSolution { public: vector<int> twoSum(vector<int>& nums, int target) { vector<pair<int, int>> vec_num_index; for (int i = 0; i < nums.size(); i++) { vec_num_index.push_back(pair(nums[i], i)); } sort(vec_num_index.begin(), vec_num_index.end());
int left = 0; int right = vec_num_index.size() - 1; while (left < right) { auto left_num = vec_num_index[left].first; auto right_num = vec_num_index[right].first; auto sum = left_num + right_num; if (sum == target) { return {vec_num_index[left].second, vec_num_index[right].second}; }