【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 日相关文章推荐
- 【LeetCode】Reverse Linked List 解题报告(Python & java)
- 【LeetCode】Binary Tree Paths 解题报告(java & python)
- 【LeetCode】Validate Binary Search Tree 解题报告(Java & Python)
- 【LeetCode】Merge Two Sorted Lists 解题报告(Java & Python)
- 【LeetCode】Group Anagrams 解题报告(Python & Java)
- 【LeetCode】Single Number 解题报告(Java & Python)
- 【LeetCode】Hamming Distance 解题报告(java & python)
- 【LeetCode】Linked List Cycle 解题报告(Java & Python)
- 【剑指Offer】重建二叉树 解题报告(Java & Python)
- 【剑指Offer】二维数组中的查找 解题报告(Java & Python)
- Leetcode 349. Intersection of Two Arrays 解题报告 Python Java
- 【剑指Offer】从尾到头打印链表 解题报告(java & python)
- [LeetCode] Pascal&#8217;s Triangle II 解题报告
- leetcode 解题 String to Integer (atoi)(C&python)
- 景岁的Leetcode解题报告:147.Insertion Sort List (Java)
- 景岁的Leetcode解题报告:283. Move Zeroes(Python)
- LeetCode 227. Basic Calculator II 解题报告【python】
- Climbing Stairs | leetcode 70 【Java解题报告】
- LeetCode 1 Two Sum 解题报告
- 【LeetCode】House Robber I & II 解题报告