Two Sum
Go to Discuss
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].
Answer:
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
sort_index = self.BubbleSort(nums)
low = 0
high = len(nums)-1
res = []
while low < high:
if nums[low] + nums[high] > target:
high -= 1
elif nums[low] + nums[high] < target:
low += 1
else:
res.append(sort_index[low])
res.append(sort_index[high])
low += 1
high -= 1
final_res = list(set(res))
return final_res
def BubbleSort(self, nums):
if nums:
nums_len = len(nums)
org_index = [i for i in range(nums_len)]
for i in range(nums_len - 1):
for j in range(nums_len - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
org_index[j], org_index[j + 1] = org_index[j + 1], org_index[j]
return org_index