LeetCode01 - 两数之和(Java 实现)

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/two-sum

题目描述

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

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

示例:

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

Java 实现与实现思路

  1. import java.util.HashMap;
  2. /**
  3. * <p>
  4. * 01:两数之和
  5. * 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
  6. * 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
  7. * </p>
  8. *
  9. * @since 2019-07-14
  10. * @author XiaoPengwei
  11. */
  12. public class LeetCode01TwoSum {
  13. public static void main(String[] args) {
  14. int[] testArr = {2, 7, 10, 32, 21};
  15. int target = 9;
  16. System.out.println("--> the method 1");
  17. int[] ints1 = method1(testArr, target);
  18. for (int i1 : ints1) {
  19. System.out.println(i1);
  20. }
  21. System.out.println("--> the method 2");
  22. int[] ints2 = method2(testArr, target);
  23. for (int i2 : ints2) {
  24. System.out.println(i2);
  25. }
  26. System.out.println("--> the method 3");
  27. int[] ints3 = method3(testArr, target);
  28. for (int i3 : ints3) {
  29. System.out.println(i3);
  30. }
  31. }
  32. /**
  33. * 方法一:暴力法
  34. * 两层循环。外层先拿出左侧第 1 个元素,内层依次判断右侧其余元素与它的和如果等于目标值则返回,如果不等于则继续下一个,如果全部遍历完不存在则抛出异常。
  35. *
  36. * @param nums 数组
  37. * @param target 和
  38. * @return int[] 下标数组
  39. */
  40. public static int[] method1(int[] nums, int target) {
  41. for (int i = 0; i < nums.length; i++) {
  42. for (int j = i + 1; j < nums.length; j++) {
  43. if (nums[j] + nums[i] == target) {
  44. return new int[]{i, j};
  45. }
  46. }
  47. }
  48. throw new IllegalArgumentException("Method1: No two sum solution");
  49. }
  50. /**
  51. * 方法二:用 Hash 表
  52. * (1)构造一个哈希表,key 是所有待选数组元素,value 是数组下标;
  53. * (2)然后从左向右遍历,对于元素 i,判断 target - nums[i] 是否包含在哈希表中,如果存在则拿出下标,如果不存在则继续。
  54. *
  55. * @param nums 数组
  56. * @param target 和
  57. * @return int[] 下标数组
  58. */
  59. public static int[] method2(int[] nums, int target) {
  60. HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  61. for (int i = 0; i < nums.length; i++) {
  62. map.put(nums[i], i);
  63. }
  64. for (int i = 0; i < nums.length; i++) {
  65. int temp = target - nums[i];
  66. if (map.containsKey(temp) && map.get(temp) != i) {
  67. return new int[]{i, map.get(temp)};
  68. }
  69. }
  70. throw new IllegalArgumentException("Method2: No two sum solution");
  71. }
  72. /**
  73. * 方法三:用 Hash 表
  74. * 可以不单独构造哈希表。这样显然在第一个元素时,不可能匹配。为什么这样也可以呢?
  75. * 其实上面我们程序结束的条件是对 2,查找是否包含 7。而这里是对 7,查找包含 2。同样可以实现。
  76. *
  77. * @param nums 数组
  78. * @param target 和
  79. * @return int[] 下标数组
  80. */
  81. public static int[] method3(int[] nums, int target) {
  82. HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
  83. for (int i = 0; i < nums.length; i++) {
  84. int temp = target - nums[i];
  85. if (map.containsKey(temp)) {
  86. return new int[]{
  87. map.get(temp), i};
  88. }
  89. map.put(nums[i], i);
  90. }
  91. throw new IllegalArgumentException("Method3: No two sum solution");
  92. }
  93. }

LeetCode01 - 两数之和(Java 实现)的更多相关文章

  1. 1. 两数之和 Java解法

    这题属于Leetcode的签到题,基本上每个人一进来就是这题. 用哈希思想来做就是最好的解答. 如果一个target - num[i] 存在那么就返回那个数字对应的下标和当前元素的下标. public ...

  2. LeetCode刷题 1. Two Sum 两数之和 详解 C++语言实现 java语言实现

    1. Two Sum 两数之和 Given an array of integers, return indices of the two numbers such that they add up ...

  3. leetCode:twoSum 两数之和 【JAVA实现】

    LeetCode 两数之和 给定一个整数数组,返回两个数字的索引,使它们相加到特定目标. 您可以假设每个输入只有一个解决方案,并且您可能不会两次使用相同的元素. 更多文章查看个人博客 个人博客地址:t ...

  4. [Java]1.两数之和 - LeetCode

    1 题目 2 思路与代码 思路一:暴力法(两层For循环) 时间复杂度:O(n^2) 对于每个元素,我们试图通过遍历数组的其余部分来寻找它所对应的目标元素,这将耗费 O(n) 的时间.因此时间复杂度为 ...

  5. Java实现 LeetCode 653 两数之和 IV - 输入 BST(递归,找差值)

    653. 两数之和 IV - 输入 BST 给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true. 案例 1: 输入: 5 / \ 3 6 / ...

  6. Java实现 LeetCode 1两数之和

    1. 两数之和 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这 ...

  7. Java实现 LeetCode 167 两数之和 II - 输入有序数组

    167. 两数之和 II - 输入有序数组 给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数. 函数应该返回这两个下标值 index1 和 index2,其中 index1 必 ...

  8. LeetCode 170. Two Sum III - Data structure design (两数之和之三 - 数据结构设计)$

    Design and implement a TwoSum class. It should support the following operations: add and find. add - ...

  9. LeetCode 371. Sum of Two Integers (两数之和)

    Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -. Exam ...

随机推荐

  1. Error:[$injector:modulerr]错误解决方式

    1.报错信息如下图所示: 问题:目前应用打包之后,在iphone6手机上打开应用白板(打开vconsole发现有如上报错  >>>  测试过多部手机,仅上面的IOS9版本出现问题) ...

  2. Python之Web前端Ajax

    Ajax: 对于WEB应用程序:用户浏览器发送请求,服务器接收并处理请求,然后返回结果,往往返回就是字符串(HTML),浏览器将字符串(HTML)渲染并显示浏览器上. 1.传统的Web应用 一个简单操 ...

  3. 【1.1】mysql frm文件丢失(ibd文件丢失)

    [1]故障模拟准备环境 这里以innodb为例 [1.1]配置参数 开启独立表空间 innodb_file_per_table; [1.2]构建测试数据 create database test; c ...

  4. 小记--------spark的两种提交模式

    spark的两种提交模式:yarn-cluster . yarn-client 图解

  5. Spring系列四:Bean Scopes作用域

    等闲识得东风面,万紫千红总是春. 概述 在Spring框架中,我们可以在六个内置的spring bean作用域中创建bean,还可以定义bean范围.在这六个范围中,只有在使用支持Web的applic ...

  6. CSS:盒子的定位与浮动

    CSS--盒子定位.浮动与居中 HTML中的每个元素都是一个盒子   浏览器对HTML文档进行解析,根据盒子的属性对其进行排列. 每个元素默认使用标准文档流定位   标准文档流:是指浏览器读取HTML ...

  7. Vue.js学习笔记-script标签在head和body的区别

    初学JavaScript,项目需要没有系统学习,只能边查资料边码代码,埋下的坑不知道有多少,还是建议时间充足的情况下系统的将Javascript学习一遍 ,涉及的HTML知识也务必了解. 问题 最开始 ...

  8. RESTful、共用接口、前后端分离、接口约定的实践 (转)

    出处:  某小公司RESTful.共用接口.前后端分离.接口约定的实践 前言 随着互联网高速发展,公司对项目开发周期不断缩短,我们面对各种需求,使用原有对接方式,各端已经很难快速应对各种需求,更难以提 ...

  9. 本地代码库,提交远程git

    1.在git上新建项目,并填好相关信息 2.新建成功后,复制项目地址 3.idea新建本地仓库 4.Add所有文件,然后提交(commit) 5.先打开push界面,设置git远程地址,然后关掉,先p ...

  10. Kafka网络模型

    摘要:很多人喜欢把RocketMQ与Kafka做对比,其实这两款消息队列的网络通信层还是比较相似的,本文就为大家简要地介绍下Kafka的NIO网络通信模型,通过对Kafka源码的分析来简述其React ...