【LeetCode】1、Two Sum
题目等级:Two Sum(Easy)
题目描述:
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].
题意:给定一个整数数组和一个指定的数,在数组找两个数使得他们的和等于这个特定数,返回他们的索引,注意一个元素不能重复使用。
解题思路:
本题实际比较简单,我们给出以下三种解法:
解法一:暴力法
这个解法就很直观了,要找两个数使其等于给定的target,两层循环当然是最暴力的解法,时间复杂度是O(n^2),没有使用额外空间,代码如下:
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res=new int[]{-1,-1};
for(int i=0;i<nums.length;i++){
for(int j=i+1;j<nums.length;j++){
if(nums[i]+nums[j]==target){
res[0]=i;
res[1]=j;
break;
}
}
}
return res;
}
}
解法二:HashMap的引入,两遍遍历
最简单的算法往往并不是最优的,上面的暴力解法用了两层循环,平方的时间复杂度往往不是我们最喜欢的,我们考虑能不能去掉一层循环。也就是说,当给定一个target,给定一个数nums[i],我们能不能不遍历直接找到有没有另一个加数,很明显,只需要判断数组中有没有target-nums[i]即可。
我们可以将数组中的数保存到hashMap中,借助HashMap的查找优势来解决,将元素值作为key,索引作为value,则常数时间我们就可以判断其中是否有target-nums[i]这个key值。
唯一需要注意的地方就是同一个元素不能重复使用。由于去掉了一层循环,因此时间复杂度变为O(n),但是这是用一个长度为n的hashmap换来的,空间复杂度为O(n),相当于一种典型的用空间换时间的算法。
class Solution {
public int[] twoSum(int[] nums, int target) {
int[] res=new int[]{-1,-1};
Map<Integer,Integer> map=new HashMap<Integer,Integer>();
for(int i=0;i<nums.length;i++){
map.put(nums[i],i);
}
for(int i=0;i<nums.length;i++){
if(map.containsKey(target-nums[i]) && map.get(target-nums[i])!=i ){
res[0]=i;
res[1]=map.get(target-nums[i]);
break;
}
}
return res;
}
}
解法三:HashMap的改进,一次遍历
上述解法二,我们可以看到对数组进行了两次遍历,第一次将其存入哈希表,第二次寻找满足条件的元素,实际上这两次循环可以合为一次,即一边存一边寻找满足条件的值。
当我们遍历到一个元素nums[i]时,可以先判断是否在哈希表中包含target-nums[i],如果存在就相当于已经找到了,不存在则将其加入哈希表,这样做的好处还有一个就是不需要判断是否重复,因为当前元素还没有加入哈希表。
这和解法二相比实际上是一个微小的改动,时间复杂度和空间复杂度都仍为O(n)。
class Solution {
public int[] twoSum(int[] nums, int target) {
/*改进:一遍遍历,利用哈希的查找优势,空间换时间*/
int[] res=new int[]{-1,-1};
Map<Integer,Integer> map=new HashMap<>();
for(int i=0;i<nums.length;i++){
int another=target-nums[i];
//注意:num还没有进哈希表,这样可以避免有重复元素的情况
if(map.containsKey(another)){ //包含target-num,则找到了对应的值
res[0]=map.get(another); //在哈希表中的是第一个
res[1]=i;
break;
}
map.put(nums[i],i); //<元素,下标>
}
return res;
}
}
总结:
本题实际比较简单。重点就在于利用hashmap的空间来换时间。
【LeetCode】1、Two Sum的更多相关文章
- 【LEETCODE】47、985. Sum of Even Numbers After Queries
package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...
- 【LeetCode】15、三数之和为0
题目等级:3Sum(Medium) 题目描述: Given an array nums of n integers, are there elements a, b, c in nums such t ...
- 【LeetCode】18、四数之和
题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...
- 【LeetCode】9、Palindrome Number(回文数)
题目等级:Easy 题目描述: Determine whether an integer is a palindrome. An integer is a palindrome when it rea ...
- 【LeetCode】 454、四数之和 II
题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...
- 【LeetCode】714、买卖股票的最佳时机含手续费
Best Time to Buy and Sell Stock with Transaction Fee 题目等级:Medium 题目描述: Your are given an array of in ...
- 【LeetCode】4、Median of Two Sorted Arrays
题目等级:Hard 题目描述: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find t ...
- 【LeetCode】2、Add Two Numbers
题目等级:Medium 题目描述: You are given two non-empty linked lists representing two non-negative integers. ...
- 【LEETCODE】38、167题,Two Sum II - Input array is sorted
package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...
随机推荐
- Android自己定义控件系列案例【五】
案例效果: 案例分析: 在开发银行相关client的时候或者开发在线支付相关client的时候常常要求用户绑定银行卡,当中银行卡号一般须要空格分隔显示.最常见的就是每4位数以空格进行分隔.以方便用户实 ...
- 我的CSDN博客停止更新通告
我的CSDN博客停止更新通告 自从2001年在CSDN发表第一篇博客開始,至今天(2014年6月11日)为止,算起来我己经在CSDN博客上"呆"了13年.共发表251篇原创文章,有 ...
- java基础--自我总结
1.带小数点数字默认为double类型,double范围比float大,为了不损失精度,double类型不会自动转换成float类型: 例:float f = 1.0f //必须这么写 2. ...
- Linux ALSA声卡驱动之七:ASoC架构中的Codec
1. Codec简介(ad/da) 在移动设备中,Codec的作用可以归结为4种,分别是: 对PCM等信号进行D/A转换,把数字的音频信号转换为模拟信号 对Mic.Linein或者其他输入源的模拟信 ...
- Python:SMOTE算法——样本不均衡时候生成新样本的算法
Python:SMOTE算法 直接用python的库, imbalanced-learn imbalanced-learn is a python package offering a number ...
- 50.Ext_数字输入框_Ext.form.NumberField
转自:https://blog.csdn.net/inflaRunAs/article/details/84033618 <mce:script type="text/javascri ...
- Android SDK Manager 无法更新问题(转载)
先看看如何加快更新速度,再说如何更新. 首先更新host文件,如图,打开目录 C:\Windows\System32\drivers\etc,在目录下有hosts文件 打开方式选用“记事本”打开 将一 ...
- cropbox
今天给大家分享一款基于jQuery头像裁剪插件cropbox,这是一款简单实用的jQuery头像在线裁剪插件.该插件适用于适用浏览器:IE8.360.FireFox.Chrome.Safari.Ope ...
- codevs1574广义斐波那契数列
1574 广义斐波那契数列 时间限制: 1 s 空间限制: 256000 KB 题目等级 : 钻石 Diamond 题目描述 Description 广义的斐波那契数列是指形如an=p* ...
- web自动化测试—selenium操作游览器属性
# coding=utf-8'''web游览器属性: 页面最大化 maximize_window() 获取当前页面地址 current_url 代码 page_source title title 后 ...