1. tag-<数组>-lt.1-两数之和Java, Python实现

梦开始的地方: 1001 two sums

案例需求

Category Difficulty Likes Dislikes
algorithms Easy (51.69%) 11714 -

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

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

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

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

提示:

2 <= nums.length <= 104
-109 <= nums[i] <= 109
-109 <= target <= 109
只会存在一个有效答案
进阶:你可以想出一个时间复杂度小于 O(n2) 的算法吗?

解法一: 暴力法(双重for循环)

1. 思路分析:

  • 由于是两个数A + B相加, 所以我们要考虑的情况比较简单, 只需要采用双重for循环,
  • 第一层循环负责遍历给定数组中的加数A(从第一个数第一种可能到倒数第二个数最后一种可能),
  • 第二层循环负责遍历加法A后面的数, 后面的数每一个都可能是符合要求的加数B,
  • 循环退出条件就是 A+B = target值.

2.1 Java代码实现:

class Solution {
    // 1. 暴力枚举
    public int[] twoSum(int[] nums, int target) {
        //结果数组 res
        int[] res = new int[2];
        //遍历数组, num[i]+剩下的num[len-i]相加, 
        //得到target立即返回 i 和 j
        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;
                }
            }
        }
        return res;
   }
  }

在这里插入图片描述

2.2 Python代码实现

相比于Java, python是如何获取遍历时的index ?
参见: 循环时获取index

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int] 
        :type target: int
        :rtype: List[int]
        """
        # 1. 索引, range(len(nums))
        # 2. enumerate(nums) --> index
        # 3. zip函数 --> zip(range(len(list)), lists)
        for i, item in enumerate(nums):
            for j in range(i + 1, len(nums)):
                if item + nums[j] == target:
                    return [i, j]            

在这里插入图片描述

解法二, HashMap 集合法

1. 思路分析

    1. 因为是两数相加=目标值, 目的是要返回两个加数的索引, 假定 加数A, 加数B, 目标值 target
    1. 为了实现复杂度为n, 我们可以对加数A进行循环, 而把加数B放在集合中,
    1. 而又因为我们既需要B的值, 还需要B的索引, 所以很自然就能想到存储 K-V对的 MAP集合(hashMap)
    1. 在hashMap中我们设置 key为加数B的值, value为加数B的索引
    1. 第一层循环对加数A进行遍历, 如果hashMap中有值满足 (target-A)了, 则返回即可.
    1. 不满足5的话, 就把这个数加入到集合中, 进行下一次遍历.

2.1 Java代码实现

class Solution{
	public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> hashMap = new HashMap<>();
        for(int i=0; i < nums.length; i++){
        	//加数A为 nums[i]
           // 判断加数B是否存在, 存在则退出循环, 返回 a和b的索引
            if(hashMap.containsKey(target - nums[i])){
                return new int[]{hashMap.get(target - nums[i]),i};
            }
             //key-num[i], value-i;
            hashMap.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}
 

在这里插入图片描述

2.2 Python代码实现

'''
python中的map.
1. 创建map --> mapxx = {}
2. 修改,添加键值对 --> mapxx[key] = balue
3. 删除键值对 --> del mapxx[key]
4. 查找键值对
	1. if key in map
	2. map.get(key, default)
'''
class Solution(Object):
	def twoSum(self, nums: List[int], target: int):
		map_j = {}	
		
		# 遍历A, 查找map中是否存在B (A+B=target), 添加B到map中(先查找再添加)
		for index, i in enumerate(nums):
			j = target - i
			
			if j in map_j:
				return [i, map_j [j]]
			map_j [j] = index

在这里借着这道题复习了以下内容:

  1. Java
  1. hashmap的基本使用
  • map的创建: Map<Integer, Integer> map = new HashMap<>(); 表明这是创建一个k-v对均是Integer类型的hashMap;
  • 查找map中的key, map.containsKey(查找的key值), 这个方法返回的是布尔值
  • map k-v键值对的插入, hashMap.put(key值, value值);
  1. 数组的基本使用
  • 直接返回一个数组: new int[]{1,2,3,4,5}, 多简洁, 还整什么建立数组, 插入值, 真的没必要!!!
  1. Python
  1. python是如何获取遍历时的index(见上面)
  2. Python中map的使用(见上面)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值