classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: n = len(nums) for i inrange(n): for j inrange(i+1, n): if nums[i] + nums[j] == target: return [i, j]
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ std::vector<int> ans; for (int i = 0; i < nums.size(); i++) { for (int j = i + 1; j < nums.size(); j++){ if (nums[i] + nums[j] == target){ return std::vector<int>{i, j}; } } } return ans; } };
哈希表
1 2 3 4 5 6 7 8 9
classSolution: deftwoSum(self, nums: List[int], target: int) -> List[int]: hashtable = dict() for k, v inenumerate(nums): tmp = target - v if tmp in hashtable: return [hashtable[tmp],k] else: hashtable[v] = k
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSolution { public: vector<int> twoSum(vector<int>& nums, int target){ unordered_map<int, int> hash_table; for (int i = 0; i < nums.size(); i++) { auto it = hash_table.find(nums[i]); if (it == hash_table.end()){ hash_table[target-nums[i]] = i; }else{ return std::vector<int>{it->second, i}; } } return {}; } };