#=================================== # Tanzila Islam # Email: tanzilamohita@gmail.com # Language: Python 3 #=================================== # Method - 1 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: dicts = {} for idx, n in enumerate(nums): x = target - n if x not in dicts: dicts[n] = idx else: return ([dicts[x], idx]) # Method - 2 class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: original = nums.copy() nums.sort() i = 0 j = len(nums)-1 nums_i = 0 nums_j = 0 idx_i = 0 idx_j = 0 while i < j: if nums[i] + nums[j] == target: #return ([i, j]) nums_i = nums[i] nums_j = nums[j] break elif nums[i] + nums[j] > target: j -= 1 else: i +=1 for idx, n in enumerate(original): if n == nums_i: idx_i = idx break for idx, n in enumerate(original): if n == nums_j and idx != idx_i: idx_j = idx break return [idx_i, idx_j]
Thursday, 13 October 2022
Array - 1. Two Sum
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment