1. Two Sum

来源:互联网 发布:安卓软件打包 编辑:程序博客网 时间:2024/06/01 14:54

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].
方法一:暴力求解

时间复杂度O(n*n)

class Solution(object):    def twoSum(self, nums, target):        result = []        count = len(nums)        for i in range(0,count):            for j in range(i+1,count):                if nums[i]+nums[j] == target:                    result.append(i)                    result.append(j)                    break        return result

方法二:Hash求解

时间复杂度O(n)

class Solution(object):    def twoSum(self, nums, target):        result = []        cnt = len(nums)        for i in range(cnt):            left = target - nums[i]            temp = nums[i]            nums[i] = '#'            if left in nums:                j = nums.index(left)                 if i<j:                    result.append(i)                    result.append(j)            nums[i] = temp        return result

注意使用index时候 有一个用例[3,3]  target = 6 比较特殊

原创粉丝点击