博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
1. Two Sum
阅读量:5900 次
发布时间:2019-06-19

本文共 3834 字,大约阅读时间需要 12 分钟。

题目:

Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

链接: 

题解:

使用HashMap,一次遍历数组。 

Time Complexity - O(n),Space Complexity - O(n)

public class Solution {    public int[] twoSum(int[] numbers, int target) {        int result[] = {-1, -1};        if(numbers == null || numbers.length == 0)            return result;        HashMap
map = new HashMap
(); for(int i = 0; i < numbers.length; i++){ if(!map.containsKey(target - numbers[i])) map.put(numbers[i], i); else{ result[0] = map.get(target - numbers[i]) + 1; result[1] = i + 1; break; } } return result; }}

 

或者可以先sort数组,再用双指针找target - numbers[i]。这样的话Time Complexity 应该是是O(nlogn), Space Complexity是O(n),就是时间复杂度换空间复杂度。 要注意sort之后原数组的index也会改变,要找到好的方法保存原数组的index。

Python:

Time Complexity - O(n), Space Complexity - O(n)

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        if len(nums) <= 1:            return False        dict = {}                for i, num in enumerate(nums):            if target - num in dict:                return dict[target - num] + 1, i + 1            else:                dict[num] = i        return -1, -1

 

Update:

class Solution(object):    def twoSum(self, nums, target):        """        :type nums: List[int]        :type target: int        :rtype: List[int]        """        if (nums is None) or (len(nums) < 2):            return -1, -1        dict = {}                for i, num in enumerate(nums):            if target - num in dict:                return dict[target - num] + 1, i + 1            else:                dict[num] = i                return -1, -1

 

二刷: 

Java: 

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

 

Python:

发现检测元素是否在dict中用 in dict比用in dict.keys()快十倍,不清楚为什么

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

 

三刷:

3/7/2016. 

有可能要考虑一下正负数的溢出

Java:

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

 

Reference:

http://www.cnblogs.com/springfor/p/3859618.html

你可能感兴趣的文章
C#基础知识整理 基础知识(21) 委托(二)
查看>>
Android应用程序键盘(Keyboard)消息处理机制分析(16)
查看>>
Sysbench 0.5版安装配置
查看>>
统一沟通-技巧-11-Lync-联盟-无法-音频-远程桌面-传文件
查看>>
书摘—你不可不知的心理策略
查看>>
【博客话题】毕业——开始人生的艰苦历程
查看>>
2014.7.30-8.3日广大网友的提问解答(答问题的第2个工作周)
查看>>
Powershell管理系列(二十五)PowerShell操作之获取AD账号及邮箱信息
查看>>
Linux安装telnet
查看>>
【高德地图API】从零开始学高德JS API(三)覆盖物——标注|折线|多边形|信息窗口|聚合marker|麻点图|图片覆盖物...
查看>>
openstack nova修改实例路径,虚拟磁盘路径
查看>>
java.sql.SQLException: Lock wait timeout exceeded --转
查看>>
使用C#进行图像处理的几种方法(转)
查看>>
Ajax原理学习
查看>>
sap scriptfom 多语言翻译
查看>>
实现超级简单的bug管理系统
查看>>
[LeetCode] Find Anagram Mappings 寻找异构映射
查看>>
--Too small initial heap for new size specified
查看>>
黄聪:3分钟学会sessionStorage用法
查看>>
Entity Framework 全面教程详解(转)
查看>>