1. 题目
给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。
你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
2. 实例
给定 nums = [2, 7, 11, 15], target = 9 因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
3. 解答
python3(用排列组合速度太慢,没过)
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ length = len(nums) index = list(range(length)) # for idx in range(length): # 可能会有负数 # if nums[idx] > target: # index.remove(idx) for i in itertools.combinations(index, 2): i_list = list(i) twosum = sum(nums[ele] for ele in i_list) if twosum == target: return i_list
python3 64ms
class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ length = len(nums) index = list(range(length)) nums_dict = dict(zip(index, nums)) nums_dict = sorted(nums_dict.items(), key=lambda x: x[1]) new_index = [ele[0] for ele in nums_dict] new_nums = [ele[1] for ele in nums_dict] for idx in range(length): value = target - new_nums[idx] if value in new_nums: value_id = new_index[new_nums.index(value)] cur_id = new_index[idx] if value_id != cur_id: return [cur_id, value_id]
4. 优答