题目

https://leetcode.com/problems/two-sum/
 

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

 
 

思路

首先考虑到时间复杂度O(N^2)的循环遍历,leetcode不能忍。

第二种方案复杂度为O(N),遍历数组时,以数值为key,索引为value建立字典,然后每次target值减当前值从字典中获取index,index小于i则说明在字典中存在。

代码O(N^2)

class Solution1:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def twoSum(self, nums, target):
rlt = []
if not nums:
return rlt
for i in range(len(nums)):
for j in range(len(nums[i+1:])):
if nums[i] + nums[i+j] == target:
rlt.append(i)
rlt.append(i+j)
return rlt

代码O(N)

class Solution:
# @param {integer[]} nums
# @param {integer} target
# @return {integer[]}
def twoSum(self, nums, target):
rlt = []
if not nums:
return rlt
num_dict = {}
for i in range(len(nums)):
if nums[i] not in num_dict:
num_dict[nums[i]] = i
print nums[i],i
j = num_dict.get(target-nums[i], -1)
if j < i and j > -1:
rlt.append(j+1)
rlt.append(i+1)
return rlt
return rlt
参考地址
1. http://blog.csdn.net/jiadebin890724/article/details/23305449

【leetcode】1. Two Sums的更多相关文章

  1. 【LeetCode】974. Subarray Sums Divisible by K 解题报告(C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 前缀和求余 日期 题目地址:https:/ ...

  2. 【leetcode】974. Subarray Sums Divisible by K

    题目如下: Given an array A of integers, return the number of (contiguous, non-empty) subarrays that have ...

  3. 【LeetCode】373. Find K Pairs with Smallest Sums 解题报告(Python)

    [LeetCode]373. Find K Pairs with Smallest Sums 解题报告(Python) 标签: LeetCode 题目地址:https://leetcode.com/p ...

  4. 【LeetCode】Minimum Depth of Binary Tree 二叉树的最小深度 java

    [LeetCode]Minimum Depth of Binary Tree Given a binary tree, find its minimum depth. The minimum dept ...

  5. 【Leetcode】Pascal&#39;s Triangle II

    Given an index k, return the kth row of the Pascal's triangle. For example, given k = 3, Return [1,3 ...

  6. 53. Maximum Subarray【leetcode】

    53. Maximum Subarray[leetcode] Find the contiguous subarray within an array (containing at least one ...

  7. 27. Remove Element【leetcode】

    27. Remove Element[leetcode] Given an array and a value, remove all instances of that value in place ...

  8. 【刷题】【LeetCode】007-整数反转-easy

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接-空 007-整数反转 方法: 弹出和推入数字 & 溢出前进行检查 思路: 我们可以一次构建反转整数的一位 ...

  9. 【刷题】【LeetCode】000-十大经典排序算法

    [刷题][LeetCode]总 用动画的形式呈现解LeetCode题目的思路 参考链接 000-十大经典排序算法

随机推荐

  1. Jump Game —— LeetCode

    Given an array of non-negative integers, you are initially positioned at the first index of the arra ...

  2. baidu面试题

    百度:http://blog.chinaunix.net/uid-26602509-id-3306451.html http://lvwenwen.iteye.com/blog/1504379

  3. UVa 11178计算几何 模板题

    #include<cstdio> #include<cstring> #include<cmath> #include<iostream> #inclu ...

  4. Jenkins 学习资料

    学习资料: iTech's Blog: Jenkins 入门总结 爱自己: 18篇博客 阳光温暖了心情: 17 篇博客 官网 参考: 构建基于Jenkins + Github的持续集成环境 CI持续集 ...

  5. 剪花布条 - HDU 2087(简单KMP | 暴力)

    分析:基础的练习............... ============================================================================ ...

  6. 005_MyEclipse编码设置

    方法一: 1.打开MyEclipse,windows---->Preferences打开"首选项"对话框. 2.左侧导航,导航中找到general---->Worksp ...

  7. backgroundworker组件的使用

    本文转载:http://www.cnblogs.com/inforasc/archive/2009/10/12/1582110.html BackgroundWorker 组件用来执行诸如数据库事务. ...

  8. python文档字符串

    #coding=utf-8 #文档字符串def d(i,j): """这个函数实现了一个乘法运算. 函数会返回一个乘法运算的结果.""" k ...

  9. OD: Vulnerabilities Analyze Skills

    第五篇了,漏洞分析案例 漏洞利用的灵活程度让这门技术变得似乎没有什么原则可言,只有实践后总结提高才能挥洒自如. 漏洞分析方法 目标:弄清攻击原理.评估潜在利用方式及风险等级.扎实的漏洞利用技术是进行漏 ...

  10. HDU5327

    #include <iostream> #include <stdio.h> #include <cstring> using namespace std; int ...