题目等级: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的更多相关文章

  1. 【LEETCODE】47、985. Sum of Even Numbers After Queries

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

  2. 【LeetCode】15、三数之和为0

    题目等级:3Sum(Medium) 题目描述: Given an array nums of n integers, are there elements a, b, c in nums such t ...

  3. 【LeetCode】18、四数之和

    题目等级:4Sum(Medium) 题目描述: Given an array nums of n integers and an integer target, are there elements ...

  4. 【LeetCode】9、Palindrome Number(回文数)

    题目等级:Easy 题目描述: Determine whether an integer is a palindrome. An integer is a palindrome when it rea ...

  5. 【LeetCode】 454、四数之和 II

    题目等级:4Sum II(Medium) 题目描述: Given four lists A, B, C, D of integer values, compute how many tuples (i ...

  6. 【LeetCode】714、买卖股票的最佳时机含手续费

    Best Time to Buy and Sell Stock with Transaction Fee 题目等级:Medium 题目描述: Your are given an array of in ...

  7. 【LeetCode】4、Median of Two Sorted Arrays

    题目等级:Hard 题目描述:   There are two sorted arrays nums1 and nums2 of size m and n respectively.   Find t ...

  8. 【LeetCode】2、Add Two Numbers

    题目等级:Medium 题目描述:   You are given two non-empty linked lists representing two non-negative integers. ...

  9. 【LEETCODE】38、167题,Two Sum II - Input array is sorted

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

随机推荐

  1. C++学习之函数模板与类模板

    泛型编程(Generic Programming)是一种编程范式,通过将类型参数化来实现在同一份代码上操作多种数据类型,泛型是一般化并可重复使用的意思.泛型编程最初诞生于C++中,目的是为了实现C++ ...

  2. 在InternetExplorer.Application中显示本地图片

    忘记了,喜欢一个人的感觉 Demon's Blog  »  程序设计  »  在InternetExplorer.Application中显示本地图片 « 对VBS效率的再思考——处理二进制数据 Wo ...

  3. cocos2d-x 多触点监听

    [cpp] view plaincopy //首先到cocos2d-x项目下的ios目录下.找到AppController.mm文件,在函数 didFinishLaunchingWithOptions ...

  4. MySQL 登录问题

    1.问题一:使用update mysql.user set password='root'改动密码后,不能登录 解决:操作过程例如以下. (1)关闭mysql(杀掉mysqld进程),然后使用命令: ...

  5. 利用jQuery Ajax技术实现每隔5秒向某页面传值

    有时候我们须要每隔一段时间向某页面传值,比方说聊天室,每隔几秒就像数据库处理页面传值并取回,然后显示在聊天窗体.又或者是每隔一段时间就查询用户最后发言时间到如今是否间隔2分钟.假设是则将用户退出. 这 ...

  6. HDU 1159 Common Subsequence (动规+最长公共子序列)

    Common Subsequence Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Other ...

  7. 树莓派玩耍笔记1 -- 开箱 &amp; 安装系统以及简单配置

    零.前言 树莓派是什么? 吃的么? 呵呵,假设您连这个还不知道,真是out 了. 麻烦出门左拐.百度去(或者,看看官网去?),算了.还是粘贴一些大家都知道的树莓派百科吧: 树莓派由注冊于英国的慈善组织 ...

  8. jsp页面设置复选框checkbox的只读效果

    提到只读,很容易想到readonly属性,但是对于复选框来说,这个属性和期望得到的效果是有差别的.原因在于readonly属性关联的是页面元素的value属性(例如text,设置了readonly就不 ...

  9. 解决:sql2005 安装完后 没有服务的问题

    去下面网站下载SQLEXPR_CHS.EXE然后安装就ok了.http://www.microsoft.com/downloadS/details.aspx?familyid=220549B5-0B0 ...

  10. C语言strdup()函数:复制字符串【转】

    本文转载自:http://c.biancheng.net/cpp/html/166.html 头文件:#include <string.h> 定义函数:char * strdup(cons ...