《中英双解》leetCode Two Sum (两数之和)

博主打算考研,所以干脆就刷英文版的了,我会把陌生的单词给整理出来,同时加上中文解释,希望大家能一起进步学习。

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: Because nums[0] + nums[1] == 9, we return [0, 1].

Example 2:

Input: nums = [3,2,4], target = 6
Output: [1,2]

Example 3:

Input: nums = [3,3], target = 6
Output: [0,1]

一些单词:

in any order:任意顺序

assume:假定,假设

add up to :合计 

 这一题是个简单题,大家都能想到的思路是,一个一个的枚举,然后加一块与target进行比较,这也是本题的第一种解法。

Brute Force(暴力枚举)

简单的说一说他的思想,就是依次对数组中两个元素遍历,相加之后与目标值比较,判断结果。现在来看看代码

public int[] twoSum(int[] nums,int target){
   for(int i = 0;i < nums.length;i++){
      for(int j = i+1;j < nums.length;j++){
         if(nums[i] + nums[j] = target){
            return new int[]{i,j}; 
         }
      }
      return null;
   }
}

这个很容易想到,不过缺点就是时间复杂度太高,O(n^2),空间复杂度为O(1)。

关于暴力匹配,大家也可以看一下我之前的博客,相信大家可以更好的理解。暴力匹配

第二个思路是用哈希表来进行解决,思路是这样的,将数组中的元素一一遍历,判断target-nums[i]是否在哈希表中,如果没有则加入哈希表,有的话就直接返回新数组中的元素。

public int[] twoSum(int[] nums,int target){
   Map<Integer,Integer> hashtable = new HashMap<>();
   for(int i = 0;i < nums.length;i++){
      if(hashtable.containsKey(target - nums[i])){
         return new int[]{hashtable.get(target - nums[i]),i};
      }
      hashtable.put(nums[i],i);
   }
   return new int[0];
}

现在给大家解读一下代码:首先创建了一个哈希表,containsKey()方法是用来判断哈希表中的key是否存在。put()方法就是用来向哈希表中存入数据的。key是nums[i]数组中的元素。value是i,数组下标。

关于哈希表我也有一篇博客,大家可以去看看:哈希表

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值