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

本题特点:

1、无序数组;

2、结果唯一;

解题1:o(nlogn)

1、对数组进行排序;o(nlogn)

2、在有序数组中寻找和等于target的两个数a,b;o(n)

解题步骤:

1、新建数组副本,并对副本排序;

2、从有序副本的两端开始查找,找到和等于target的两个数,记录其下标为i和j;

3、两遍遍历原数组,第一遍寻找a[i]的原始位置index1,第二遍寻找a[j]的原始位置index2;(比一遍遍历具有更少的比较次数)

4、按照从小到大的顺序生成返回数组,返回index1和index2;

注意:

1、原数组中可能包含重复的元素;

2、不能使用原数组排序,本题需要记录原数组元素顺序。即使不需要原始顺序,如无特殊要求,也不应该在函数内对原数组进行操作;

3、同时,此题在细节的时间复杂度要求非常苛刻(亲测):

  ①、即使相同时间复杂度的排序算法,也有很大区别,此题排序时必须使用最优秀的nlogn算法,即STL源码中使用的优化改进后的快速排序算法;我使用了标准堆排序算法,未能通过;

  ②、对数组元素进行比较和交换操作,不如先对整数进行比较和交换,然后再赋值给数组;

  ③、减少所有不必要的赋值、比较和交换操作;

代码:

 class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
int length = numbers.size();
vector<int> numbers_copy = numbers;
sort(numbers_copy.begin(), numbers_copy.end()); int i = ;
int j = length - ;
while (i < j) {
if (numbers_copy[i] + numbers_copy[j] < target)
i++;
else if (numbers_copy[i] + numbers_copy[j] > target)
j--;
else
break;
} int index1 = ;
int index2 = length - ;
while(index1 < length && numbers_copy[i] != numbers[index1])
index1++;
while(index2 > && numbers_copy[j] != numbers[index2])
index2--;
if (index1 > index2)
swap(index1, index2); vector<int> result {index1 + , index2 + };
return result;
}
};

解题2:

使用哈希表,使查找的复杂度为o(1),达到o(n)时间复杂度;

解题步骤:

1、新建一个两元素数组作为返回数组,再新建一个hash表结构;

2、遍历原始数组,遇到的每一个元素i:

  如果hash表中已存在target - a[i],则a[i]和target - a[i]就是要找的两个数,且target-a[i]先出现;

  如果hash表中不存在,则将键a[i]传入hash表,值设置为其下标值i;(注意此时hash表中可能已经存在a[i])

代码:

 class Solution {
public:
vector<int> twoSum(vector<int> &numbers, int target) {
vector<int> result();
unordered_map<int, int> hmap;
int length = numbers.size();
for (int i = ; i < length; ++i) {
if (hmap.find(target - numbers[i]) != hmap.end()) {
result[] = hmap[target - numbers[i]] + ;
result[] = i + ;
return result;
} else {
hmap[numbers[i]] = i;
}
}
return result;
}
};

【Leetcode】【Medium】Two Sum的更多相关文章

  1. 【LeetCode题意分析&解答】40. Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  2. 【LeetCode题意分析&解答】37. Sudoku Solver

    Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...

  3. 【LeetCode题意分析&解答】35. Search Insert Position

    Given a sorted array and a target value, return the index if the target is found. If not, return the ...

  4. ACM金牌选手整理的【LeetCode刷题顺序】

    算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...

  5. 【LeetCode每天一题】Minimum Path Sum(最短路径和)

    Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which ...

  6. 【leetcode刷题笔记】Combination Sum II

    Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...

  7. 【leetcode刷题笔记】Path Sum

    Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all ...

  8. 【leetcode刷题笔记】Sum Root to Leaf Numbers

    Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number ...

  9. 【LeetCode题意分析&解答】39. Combination Sum

    Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...

  10. 【LeetCode每天一题】Combination Sum II(组合和II)

    Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...

随机推荐

  1. POST请求出现中文乱码的问题

    最近使用Java的HttpURLConnection请求rest接口时候,POST请求参数中的中文传输之后出现乱码的问题,在网上找了一个亲测有效的方法: 将 DataOutputStream out ...

  2. 关于 vertical-align 的一些小知识

    引子 在日常开发过程中,我们经常会遇到如下的场景,一行中既有图片也有文字,而且图片还要和文字对齐.效果如下: 通常代码如下: <!DOCTYPE html> <html> &l ...

  3. linux 查看端口,开启新端口

    一.查看端口被占用命令 1.lsof -i:端口号 2.netstat -tunlp|grep 端口号 3.netstat -anp 查看哪些端口被打开 上面命令是查看端口被进程占用的情况 二.开启新 ...

  4. 九度oj题目1342:寻找最长合法括号序列II

    题目1342:寻找最长合法括号序列II(25分) 时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:886 解决:361 题目描述: 假如给你一个由’(‘和’)’组成的一个随机的括号序列,当然 ...

  5. 【转】HttpWebRequest 保持session

    通过HttpWebRequest获取网页内容并保持session,最主要的就是存储cookie.这里使用了一个静态变量m_Cookie用来存储cookie的内容.第二次请求网页的时候把cookie传送 ...

  6. Expression Blend实例中文教程(7) - 动画基础快速入门Animation

    通过前面文章学习,已经对Blend的开发界面,以及控件有了初步的认识.本文将讲述Blend的一个核心功能,动画设计.大家也许注意到,从开篇到现在,所有的文章都是属于快速入门,是因为这些文章,都是我曾经 ...

  7. C#基础知识-使用XML完成一个小程序(十一)

    上一篇中讲到XML基本的结构,还有增删改查的方法,这一篇中我们就来利用XML来完成一个简单的订单系统,主要是实现一个简单学生名单的增删改查,如果想要应用到实际的环境中建议考虑数据量的问题,如果数据量大 ...

  8. sublime text 2编辑器中文问题

    Sublime Text 2是一个非常不错的源代码及文本编辑器,但是不支持GB2312和GBK编码在很多情况下会非常麻烦.不过Sublime Package Control所以供的插件可以让Subli ...

  9. Nginx - 简易图片服务器

    安装 主要使用Nginx和vsftpd. 安装方面可以直接从nginx官网上下载,或者... yum install nginx 如果没有yum源则需要自行添加再进行install. yum inst ...

  10. java中list、set、map区别(转)

    Collection├List│├LinkedList│├ArrayList│└Vector│ └Stack└SetMap├Hashtable├HashMap└WeakHashMap Collecti ...