https://leetcode.com/problems/two-sum/
Given an array of integers, return indices of the two numbers such that they add up to a specific target. You may assume that each input would have exactly one solution, and you may not use the same element twice. Example: Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
class Solution { public: vectortwoSum(vector & nums, int target) { } };
class Solution { public: vectortwoSum(vector & nums, int target) { int i1, i2; int found = 0; for (i1 = 0; i1 < nums.size(); i1 ++){ int val1 = nums[i1]; int val2 = target - val1; for (i2 = i1+1; i2 < nums.size(); i2 ++){ if (nums[i2] == val2){ found = 1; break; } } if (found == 1) break; } vector solution; solution.push_back(i1); solution.push_back(i2); return solution; } };
class Solution { public: vectortwoSum(vector & nums, int target) { vector nums_sorted = nums; std::sort(nums_sorted.begin(), nums_sorted.end()); int i1 = 0; int i2 = nums_sorted.size() -1; while (i2 > i1){ int sum = nums_sorted[i1] + nums_sorted[i2]; if (sum == target) break; if (sum > target) i2 --; else i1 ++; } int val1 = nums_sorted[i1]; int val2 = nums_sorted[i2]; i1 = -1; i2 = -1; for (int i = 0; i < nums.size(); i ++){ if (i1 > -1 && i2 > -1) break; if (i1 == -1 && nums[i] == val1) i1 = i; else if (i2 == -1 && nums[i] == val2) i2 = i; } vector solution; solution.push_back(i1); solution.push_back(i2); return solution; } };
class Solution { public: vectortwoSum(vector & nums, int target) { # first check if there's 2 target/2 element in the vector vector solution; map map_val_idx; for (int idx1 = 0; idx1 < nums.size(); idx1 ++){ int val1 = nums[idx1]; int val2 = target - val1; map ::iterator it = map_val_idx.find(val2); if (it != map_val_idx.end()){ solution.push_back(idx1); solution.push_back(it->second); break; }else{ map_val_idx.insert(std::pair (val1, idx1) ); } } return solution; } };