1. 题目  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

给定一个整数数组,找出其中两个数满足相加等于你指定的目标数字。

要求:这个函数twoSum必须要返回能够相加等于目标数字的两个数的索引,且index1必须要小于index2。请注意一点,你返回的结果(包括index1和index2)都不是基于0开始的。

你可以假设每一个输入肯定只有一个结果。

2. c++解题

2.1  两层循环,时间复杂度为o(n^2),空间复杂度为o(1)

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
for (int i = 0; i < numbers.size()-1; i++) {
for (int j = i+1; j < numbers.size(); j++) {
if (numbers[i] + numbers[j]==target) {
result.push_back(i+1);
result.push_back(j+1);
return result;
}
}
}
return result;
}
};

2.2 哈希,时间复杂度为o(n),空间复杂度为o(n)

class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result;
map<int, int> m;
if (numbers.size() < 2)
return result;
for (int i = 0; i < numbers.size(); i++)
m[numbers[i]] = i; map<int, int>::iterator it;
for (int i = 0; i < numbers.size(); i++) {
if ((it = m.find(target - numbers[i])) != m.end())
{
if (i == it->second) continue;
result.push_back(i+1);
result.push_back(it->second+1);
return result;
}
}
return result;
}
};

3. python 解题

  将原来的数组深拷贝一份,然后排序---然后在排序后的数组中找两个数使它们相加为target:使用两个指针,一个指向头,一个指向尾,两个指针向中间移动并检查两个指针指向的数的和是否为target。如果找到了这两个数,再将这两个数在原数组中的位置找出来就可以了---要注意的一点是:在原来数组中找下标时,需要一个从头找,一个从尾找,要不无法通过。如这个例子:numbers=[0,1,2,0]; target=0。如果都从头开始找,就会有问题。

3.1

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        index = []
        numtosort = num[:] //深拷贝
     numtosort.sort()
        i = 0; j = len(numtosort) - 1
        while i < j:
            if numtosort[i] + numtosort[j] == target:
                for k in range(0,len(num)):
                    if num[k] == numtosort[i]:
                        index.append(k)
                        break
                for k in range(len(num)-1,-1,-1):
                    if num[k] == numtosort[j]:
                        index.append(k)
                        break
                index.sort()
                break
            elif numtosort[i] + numtosort[j] < target:
                i = i + 1
            elif numtosort[i] + numtosort[j] > target:
                j = j - 1         return (index[0]+1,index[1]+1)

3.2 字典

class Solution:
    # @return a tuple, (index1, index2)
    def twoSum(self, num, target):
        dict = {}
        for i in range(len(num)):
            x = num[i]
            if target-x in dict:
                return (dict[target-x]+1, i+1) //找到,返回两数的下标
            dict[x] = i

4. JAVA 哈希

public class Solution {
public static int[] twoSum(int[] numbers, int target) {
int[] res = new int[2];
HashMap<Integer, Integer> nums = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; ++i) {
// add i-th number
Integer a = nums.get(numbers[i]);
if (a == null)
nums.put(numbers[i], i); // find (target - numbers[i])
a = nums.get(target - numbers[i]);
if (a != null && a < i) {
res[0] = a ;
res[1] = i ;
break;
}
}
return res;
}
}
												

leetcode——1的更多相关文章

  1. 我为什么要写LeetCode的博客?

    # 增强学习成果 有一个研究成果,在学习中传授他人知识和讨论是最高效的做法,而看书则是最低效的做法(具体研究成果没找到地址).我写LeetCode博客主要目的是增强学习成果.当然,我也想出名,然而不知 ...

  2. LeetCode All in One 题目讲解汇总(持续更新中...)

    终于将LeetCode的免费题刷完了,真是漫长的第一遍啊,估计很多题都忘的差不多了,这次开个题目汇总贴,并附上每道题目的解题连接,方便之后查阅吧~ 477 Total Hamming Distance ...

  3. [LeetCode] Longest Substring with At Least K Repeating Characters 至少有K个重复字符的最长子字符串

    Find the length of the longest substring T of a given string (consists of lowercase letters only) su ...

  4. Leetcode 笔记 113 - Path Sum II

    题目链接:Path Sum II | LeetCode OJ Given a binary tree and a sum, find all root-to-leaf paths where each ...

  5. Leetcode 笔记 112 - Path Sum

    题目链接:Path Sum | LeetCode OJ Given a binary tree and a sum, determine if the tree has a root-to-leaf ...

  6. Leetcode 笔记 110 - Balanced Binary Tree

    题目链接:Balanced Binary Tree | LeetCode OJ Given a binary tree, determine if it is height-balanced. For ...

  7. Leetcode 笔记 100 - Same Tree

    题目链接:Same Tree | LeetCode OJ Given two binary trees, write a function to check if they are equal or ...

  8. Leetcode 笔记 99 - Recover Binary Search Tree

    题目链接:Recover Binary Search Tree | LeetCode OJ Two elements of a binary search tree (BST) are swapped ...

  9. Leetcode 笔记 98 - Validate Binary Search Tree

    题目链接:Validate Binary Search Tree | LeetCode OJ Given a binary tree, determine if it is a valid binar ...

  10. Leetcode 笔记 101 - Symmetric Tree

    题目链接:Symmetric Tree | LeetCode OJ Given a binary tree, check whether it is a mirror of itself (ie, s ...

随机推荐

  1. C#回调函数的简单讲解与应用例子

    using System; namespace CallBackTest{ class Program //用户层,执行输入等操作 { static void Main(string[] args) ...

  2. IIS 找不到.net framework 4.0/4.5程序池

    通常情况下是因为没注册造成的,也有可能跟操作系统有关系 以管理员身份运行cmd   打开我的电脑 C:\Windows\System32\cmd.exe,右键以管理员身份运行 然后:C:\WINDOW ...

  3. VS Code 缩小

    一.问题描述 当我们在使用 Visual Studio Code 时,放大,我们可以使用 “ CTRL + ” 快捷键来实现.在使用 “ CRRL - ” 快捷键,缩小不了,我们怎么办? 二.解决方案 ...

  4. burpsuite 抓HTTPS数据包

    抓HTTPS数据包 导出保存为cer证书文件,导入到受信任的根证书颁发机构 设置代理服务器与burp中proxy listeners保持一致 设置目标url 抓包 可用repeater发请求

  5. 获取.net应用的版本及依赖信息

    在制作打包安装器时,通常要获取要安装的程序的名称.版本.说明,以及依赖的版本信息,经过翻阅MSDN,stackoverflow,终于搞定了. 1. 获取应用的依赖信息 var ans = System ...

  6. 「模拟赛20180306」回忆树 memory LCA+KMP+AC自动机+树状数组

    题目描述 回忆树是一棵树,树边上有小写字母. 一次回忆是这样的:你想起过往,触及心底--唔,不对,我们要说题目. 这题中我们认为回忆是这样的:给定 \(2\) 个点 \(u,v\) (\(u\) 可能 ...

  7. 安装篇:MySQL系列之一

    环境:CentOS6.9系统安装MariaDB-10.2.15 一.yum包管理器安装MariaDB-server ​ 1)配置yum源(MariaDB官方源) [root@centos6 ~]# v ...

  8. uoj455 【UER #8】雪灾与外卖

    http://uoj.ac/problem/455 题解: https://blog.csdn.net/litble/article/details/88410435 https://www.mina ...

  9. js 监听浏览器刷新还是关闭事件

    转载大神 http://www.cnblogs.com/gavin0517/p/5827405.html

  10. HQL和SQL

    hql是面向对象查询,格式:from + 类名 + 类对象 + where + 对象的属性 sql是面向数据库表查询,格式:from + 表名 + where + 表中字段 1.查询 一般在hiber ...