两数之和 Two Sum
给定一个整数数列,找出其中和为特定值的那两个数。
你可以假设每个输入都只会有一种答案,同样的元素不能被重用。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]
方法一
使用i,j遍历数组nums中的每一个变量,验证nums[i]+nums[j]是否等于target
代码如下:
public static int[] twoSum(int[] nums, int target) {
int N = nums.length;
for (int i=0; i<N-1; i++)
for (int j=i+1; j<N; j++)
if (nums[i] + nums[j] == target)
return new int[] {i,j};
return null;
}
此方法的复杂度为O(N^2)
方法二
使用HashMap存储nums的值及对应的下标
定义变量c=target-nums[i],在map中寻找是否存在键值为c
代码如下:
public static int[] twoSumMap(int[] nums, int target) {
int N = nums.length;
Map<Integer, Integer> map = new HashMap<>();
// nums的值为key,下标为value
for (int i=0; i<N; i++)
map.put(nums[i], i);
for (int i=0; i<N-1; i++) {
int complement = target - nums[i];
// 找到的键值不能为i
if (map.containsKey(complement) && map.get(complement)!=i)
return new int[] {i, map.get(complement)};
}
return null;
}
复杂度分析:
将nums存入map中,空间复杂度O(N)
for循环寻找两个下标,时间复杂度为O(N)
该方法中,键值为数组值,value为数组下标,故数组中数值相等的元素在map中只存储了一次。
如nums[] = {2, 5, 5, 6}, map中为2-0, 5-2, 6-3,但这并不影响该算法找到正确的答案
另外,若数组nums为有序的,则可以使用两个指针分别指向数组的首尾两个元素。
比较两个元素的和与target,根据比较结果移动指针,直到两指针相遇或找到结果
实现代码如下:
public static int[] twoSumOrder(int[] nums, int target) {
int i = 0;
int j = nums.length - 1;
while (i != j) {
if (nums[i] + nums[j] == target)
return new int[] {i,j};
else if (nums[i] + nums[j] > target)
j--;
else
i++;
}
return null;
}
复杂度为O(N)
两数之和 Two Sum的更多相关文章
- 领扣-1/167 两数之和 Two Sum MD
Markdown版本笔记 我的GitHub首页 我的博客 我的微信 我的邮箱 MyAndroidBlogs baiqiantao baiqiantao bqt20094 baiqiantao@sina ...
- [Swift]LeetCode1 .两数之和 | Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific ta ...
- c++谭浩强教材教学练习例题1.2 求两数之和 为什么sum=a+b;sum的值为65538
第一章 #include <iostream>using namespace std; int main(){ int a,b,sum; sum=a+b; cin>>a> ...
- LeetCode 1:两数之和 Two Sum
题目: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数组中 ...
- 1.两数之和(Two Sum) C++
暴力法可解决,速度很慢. 解决办法:哈希表 知识点: map的构造 遍历map使用迭代器,判断条件 插入 pair<int,int> 寻找key是否存在 class Solution { ...
- LeetCode 653. 两数之和 IV - 输入 BST(Two Sum IV - Input is a BST)
653. 两数之和 IV - 输入 BST 653. Two Sum IV - Input is a BST 题目描述 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定 ...
- LeetCode_#1_两数之和 Two Sum_C++题解
1. 两数之和 Two Sum 题目描述 Given an array of integers, return indices of the two numbers such that they ad ...
- LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$
Design and implement a TwoSum class. It should support the following operations: add and find. add - ...
- LeetCode 371. Sum of Two Integers (两数之和)
Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...
随机推荐
- Java远程调试 java -Xdebug各参数说明
JAVA自身支持调试功能,并提供了一个简单的调试工具--JDB,类似于功能强大的GDB,JDB也是一个字符界面的 调试环境,并支持设置断点,支持线程线级的调试 JAVA的调试方法如下: 1.首先支持J ...
- DB2性能调优
1.更新统计信息 --更新数据库所有表统计信息 --连接到数据库(-v选项,表示要回显命令,以下同) db2 -v connect to DB_NAME --查看是否收集过统计信息,什么时候更新的 ...
- python 绘图 异常点绘制使用 ax.plot(abnormal_points['ds'], abnormal_points['y'], "rX", label='abnormal points')
from matplotlib import pyplot as plt def my_plot(title, m, fcst, ax=None, uncertainty=True, plot_cap ...
- 关于向后台请求数据(get请求,无参数传递),返回html代码(实际需要返回的是json数据)的解决方案
this.$http.get(apis.schoolVideo, { headers: { 'X-Requested-With': 'XMLHttpRequest' } }) 待续
- flex布局学习总结
最近项目主要是小程序,小程序里面的布局主要采用flex布局,之前对flex 布局只是稍作了解,总结下flex 布局的常用套路 容器 Flex是Flexible Box的缩写,意为"弹性布局& ...
- 微信小程序--登录流程梳理
前言 微信小程序凡是需要记录用户信息都需要登录,但是也有几种不同的登录方式,但是在小程序部分的登录流程是一样的.之前就朦朦胧胧地用之前项目的逻辑改改直接用了,这个新项目要用就又结合官方文档重新梳理了下 ...
- learning uboot support web http function in qca4531 cpu
reference :https://forum.openwrt.org/viewtopic.php?id=43237 reference :http://blog.chinaunix.net/uid ...
- 跟我一起学习ASP.NET 4.5 MVC4.0(五)
前面几篇文章介绍了一下ASP.NET MVC中的一些基础,今天我们一起来学习一下在ASP.NET MVC中控件的封装.在页面中我们会经常使用到Html对象,来程序控件,当然这里的控件不是说ASP.NE ...
- Python sqlalchemy使用
import sqlalchemy from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declar ...
- 关于c++显示调用析构函数的陷阱
版权声明:欢迎转载,注明出处就好!如果不喜欢请留言说明原因再踩哦,谢谢,我也可以知道原因,不断进步!! 目录(?)[+] 一.文章来由 现在在写一个项目,需要用到多叉树存储结构,但是在某个时候 ...