LeetCode Two Sum-C ++、Python



Leetcode Two Sum C Python



タイトルリンク: 2つの合計

C ++



//C++ //Approach 1:Brute Force //Time complexity O(n^2), space complexity O(1) class Solution{ public: vector twoSum(vector& nums, int target){ vector ret int flag=0 for(int i=0 isecond!=i indicates that the subscript is not equal to the current value { ret.push_back(i) ret.push_back(it->second) break } } return ret } } //Approach 3:One-pass Hash Table //Time complexity O(n), space complexity O(n), map traverse once class Solution{ public: vector twoSum(vector& nums, int target){ vectorret maptemp map::iterator it for(int i=0isecond!=i){ ret.push_back(i) ret.push_back(it->second) break } temp.insert(pair(nums[i],i)) } return ret } }

Python

#Approach 1 class Solution: def twoSum(self,nums: List[int], target:int) ->List[int]: len1 = len(nums) flag = 0 for i in range(0,len1): for j in range(i+1,len1): if(nums[i]+nums[j]==target): flag=1 return [i,j] #Approach 2 class Solution: def twoSum(self,nums: List[int], target:int) ->List[int]: hashtable = {value: index for index,value in enumerate(nums)} for index,value in enumerate(nums): result = target - value hash_index = hashtable.get(result) if hash_index and hash_index !=index: return [index,hash_index] #Approach 3 class Solution: def twoSum(self, nums: List[int], target:int)->List[int]: hash_table={} for i in range(len(nums)): result = target - nums[i] if result in hash_table.keys(): return [i,hash_table[result]] else: hash_table[nums[i]]=i return