您的位置:首页 > 编程语言 > Python开发

【LeetCode】Two Sum 解题报告(java & python)

2017-05-18 13:31 555 查看

【LeetCode】Two Sum 解题报告(java & python)

标签(空格分隔): LeetCode

题目地址:https://leetcode.com/problems/two-sum/#/description

题目描述:

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].


Ways

这个题首先想到的是时间复杂度O(n^2)的遍历,但是肯顶会超时,所以想到用HashMap保存已经有的数据出现的额位置,这样可以使如果要求的数字出现的时候不再继续遍历,及时停止即可。有个技巧就是判断差是否在HashMap中,而不是遍历一遍HashMap来求和。

public class Solution {
public int[] twoSum(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for(int i = 0; i < nums.length; i++){
if(map.containsKey(target - nums[i])){
return new int[]{map.get(target - nums[i]), i};
}else{
map.put(nums[i], i);
}
}
return new int[2];
}
}


二刷,用的python,更简单一点。

class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
dic = {}
for i, num in enumerate(nums):
dic[num] = i
for i, num in enumerate(nums):
if target - num in dic and dic[target - num] != i:
return [i, dic[target - num]]


Date

2017 年 5 月 18 日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: