Python编程实践操作教程:两数之和—Java和Python的代码对比

发布时间:2020-08-10 07:06:03 作者:千锋Python唐小强
来源:ITPUB博客 阅读:165

Python编程实践操作教程:两数之和,分别用Java和Python表现!伙伴们可以做个对比!

题目:

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

Python编程实践操作教程:两数之和—Java和Python的代码对比

示例:

给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

解题思路:

哈希表:哈希映射(map、dict),key 保存该元素,value 保存该元素索引。

例:nums = [2, 11, 7, 15], target = 9, hashmap = { }
遍历:
i = 0: target - x = 9 - 2 = 7, 7 不存在于 hashmap 中,则 x(2) 加入 hashmap, hashmap = {2 : 0}
i = 1: target - x = 9 - 11 = -2, -2 不存在于 hashmap 中,则 x(-2) 加入 hashmap, hashmap = {2 : 0, 11 : 1}
i = 2: target - x = 9 - 7 = 2, 2 存在于 hashmap 中,则返回列表 [2, 0]

代码:

两次遍历(Java):

class Solution {
 public int[] twoSum(int[] nums, int target) {
 Map<Integer, Integer> map = new HashMap<>();
 for (int i = 0; i < nums.length; i++) {//一次遍历转换成键值对,key为元素值,value为索引值
 map.put(nums[i], i);
 }
 for (int i = 0; i < nums.length; i++) {//二次遍历查找符合条件的元素
 int res = target - nums[i];
 if (map.containsKey(res) && map.get(res) != i) {//查找到的目标元素不能为其本身
 return new int[]{i, map.get(res)};
 }
 }
 return null;
 }
}

一次遍历 (Java):

class Solution {
 public int[] twoSum(int[] nums, int target) {
 Map<Integer, Integer> map = new HashMap<>();
 for (int i = 0; i < nums.length; i++) {
 int res = target - nums[i];
 if (map.containsKey(res)) {//因为自身元素还未加入到 hashmap,无需 map.get(res) != i 条件判断
 return new int[]{i, map.get(res)};
 }
 map.put(nums[i], i);//未找到目标元素则将其加入 hashmap
 }
 return null;
 }
}

一次遍历 (Python):

class Solution:
 def twoSum(self, nums: List[int], target: int) -> List[int]:
 dic = {}
 for i, num in enumerate(nums): #枚举 nums 数组
 if num in dic:
 return [dic[num], i]
 else:
 dic[target-num] = i

利用 Python 数组自带 index 方法解题:

class Solution:
 def twoSum(self, nums: List[int], target: int) -> List[int]:
 for i, num in enumerate(nums):
 if target-num in nums and nums.index(target-num) != i:
 return [i, nums.index(target-num)]

list.index():

描述:

index () 函数用于从列表中找出某个值第一个匹配项的索引位置。

语法:

index () 方法语法:

list.index(x, start, end)

参数:

返回:

该方法返回查找对象的索引位置,如果没有找到对象则抛出异常。

有不清楚的地方可以留言或者私信!

推荐阅读:
  1. python怎么求两数之和
  2. JS如何求解两数之和

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

java python 两数

上一篇:计算机操作系统操作及专业化软硬件操作

下一篇:好程序员Java学习路线JSP对象

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》