【Leetcode】【Medium】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
本题特点:
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的更多相关文章
- 【LeetCode题意分析&解答】40. Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【LeetCode题意分析&解答】37. Sudoku Solver
Write a program to solve a Sudoku puzzle by filling the empty cells. Empty cells are indicated by th ...
- 【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 ...
- ACM金牌选手整理的【LeetCode刷题顺序】
算法和数据结构知识点图 首先,了解算法和数据结构有哪些知识点,在后面的学习中有 大局观,对学习和刷题十分有帮助. 下面是我花了一天时间花的算法和数据结构的知识结构,大家可以看看. 后面是为大家 精心挑 ...
- 【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 ...
- 【leetcode刷题笔记】Combination Sum II
Given a collection of candidate numbers (C) and a target number (T), find all unique combinations in ...
- 【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 ...
- 【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 ...
- 【LeetCode题意分析&解答】39. Combination Sum
Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C wher ...
- 【LeetCode每天一题】Combination Sum II(组合和II)
Given a collection of candidate numbers (candidates) and a target number (target), find all unique c ...
随机推荐
- Linux工具安装配置之Oracle
对于Oracle的安装真的是心生恐惧,特别是一堆堆的依赖包.趁这次DBA在南京,实际操作一番. 两种方式,1.全新安装:2.硬拷贝 全新安装,参考下面这个介绍 http://www.cnblogs.c ...
- opencv-python 读入带有中文的图片路径
windows 下读入带有中文的图片路径使用cv2.imread() 不能读入.使用如下代码可以. def cv_imread(filePath): cv_img = cv2.imdecode(np. ...
- JS及Dom练习 | 页面滚动文字
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Python爬虫抓取某音乐网站MP3(下载歌曲、存入Sqlite)
最近右胳膊受伤,打了石膏在家休息.为了实现之前的想法,就用左手打字.写代码,查资料完成了这个资源小爬虫.网页爬虫, 最主要的是协议分析(必须要弄清楚自己的目的),另外就是要考虑对爬取的数据归类,存储. ...
- 聚焦小游戏技术生态,腾讯游戏云GAME-TECH落地厦门
欢迎大家前往腾讯云+社区,获取更多腾讯海量技术实践干货哦~ 本文由腾讯游戏云 发表于云+社区专栏 2018迎来了小游戏元年,据<2018年小游戏行业白皮书>显示:2018年小游戏市场规模预 ...
- CF 675D——Tree Construction——————【二叉搜索树、STL】
D. Tree Construction time limit per test 2 seconds memory limit per test 256 megabytes input standar ...
- .netCore2.0 WebApi 传递form表单
随着it的技术发展,目前越来越多的项目采用前后端分离的开发模式,通过webapi提供接口数据来进行交互 最近项目用的是.netCore WebApi,在最近的项目使用中发现一些问题,进行记录.个人简介 ...
- android socket 通讯(客户端) 发送数据
/** ClientSocket通讯类 **/ public class ClientSocket { /**服务器地址*/ private String serverUrl=&q ...
- A space or line break was encountered after the "@" character. Only valid identifiers, keywords, comments, "(" and "{" are valid at the start of a code block and they must occur immediately following
mvc 控制器调用分布视图出错,("A space or line break was encountered after the "@" character. Only ...
- [android] 练习使用ListView(三)
解决OOM和图片乱序问题 package com.android.test; import java.io.InputStream; import java.net.HttpURLConnection ...