LeetCode01 - 两数之和(Java 实现)

来源:力扣(LeetCode)

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

题目描述

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

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

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]

Java 实现与实现思路

import java.util.HashMap;

/**
* <p>
* 01:两数之和
* 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
* 你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。
* </p>
*
* @since 2019-07-14
* @author XiaoPengwei
*/
public class LeetCode01TwoSum { public static void main(String[] args) { int[] testArr = {2, 7, 10, 32, 21};
int target = 9; System.out.println("--> the method 1");
int[] ints1 = method1(testArr, target);
for (int i1 : ints1) {
System.out.println(i1);
} System.out.println("--> the method 2");
int[] ints2 = method2(testArr, target);
for (int i2 : ints2) {
System.out.println(i2);
} System.out.println("--> the method 3");
int[] ints3 = method3(testArr, target);
for (int i3 : ints3) {
System.out.println(i3);
}
} /**
* 方法一:暴力法
* 两层循环。外层先拿出左侧第 1 个元素,内层依次判断右侧其余元素与它的和如果等于目标值则返回,如果不等于则继续下一个,如果全部遍历完不存在则抛出异常。
*
* @param nums 数组
* @param target 和
* @return int[] 下标数组
*/
public static int[] method1(int[] nums, int target) { for (int i = 0; i < nums.length; i++) {
for (int j = i + 1; j < nums.length; j++) {
if (nums[j] + nums[i] == target) {
return new int[]{i, j};
}
} }
throw new IllegalArgumentException("Method1: No two sum solution");
} /**
* 方法二:用 Hash 表
* (1)构造一个哈希表,key 是所有待选数组元素,value 是数组下标;
* (2)然后从左向右遍历,对于元素 i,判断 target - nums[i] 是否包含在哈希表中,如果存在则拿出下标,如果不存在则继续。
*
* @param nums 数组
* @param target 和
* @return int[] 下标数组
*/
public static int[] method2(int[] nums, int target) {
HashMap<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++) {
int temp = target - nums[i];
if (map.containsKey(temp) && map.get(temp) != i) {
return new int[]{i, map.get(temp)};
}
} throw new IllegalArgumentException("Method2: No two sum solution");
} /**
* 方法三:用 Hash 表
* 可以不单独构造哈希表。这样显然在第一个元素时,不可能匹配。为什么这样也可以呢?
* 其实上面我们程序结束的条件是对 2,查找是否包含 7。而这里是对 7,查找包含 2。同样可以实现。
*
* @param nums 数组
* @param target 和
* @return int[] 下标数组
*/
public static int[] method3(int[] nums, int target) {
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
for (int i = 0; i < nums.length; i++) {
int temp = target - nums[i];
if (map.containsKey(temp)) {
return new int[]{
map.get(temp), i};
}
map.put(nums[i], i);
} throw new IllegalArgumentException("Method3: No two sum solution");
}
}

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. 安装neutron

    在控制节点上执行 controllerHost='controller' MYSQL_PASSWD='m4r!adbOP' RABBIT_PASSWD='0penstackRMQ' NOVA_PASS ...

  2. 【DSP开发】串行 RapidIO: 高性能嵌入式互连技术

    串行 RapidIO: 高性能嵌入式互连技术 作者: 德州仪器技术应用工程师 冯华亮/ Brighton Feng/ bf@ti.com 摘要 串行RapidIO针对高性能嵌入式系统芯片间和板间互连而 ...

  3. 使用vue-lbsmap快速开发地图应用/GPSBD

    vue-lbsmap是一款基于vue的WebGIS地图插件,经过我们多年实际项目应用中积累的技术,打造的灵活.易用.数据驱动型插件,可以帮助您快速开展地图业务层的应用开发,完全免费 <!DOCT ...

  4. 向指定用户发送WebSocket消息并处理对方不在线的情况

    使用SimpMessagingTemplate发送消息 使用org.springframework.messaging.simp.SimpMessagingTemplate类可以在服务端的任意地方给客 ...

  5. C语言Ⅰ博客作业09

    这个作业属于那个课程 C语言程序设计II 这个作业要求在哪里 https://edu.cnblogs.com/campus/zswxy/CST2019-3/homework/10029 我在这个课程的 ...

  6. VirtualBox本地虚拟机常见问题

    SSH连接本地虚拟机配置 https://www.jianshu.com/p/d59ed9f226d1 开启双向复制https://blog.csdn.net/wcx1293296315/articl ...

  7. PTA(Advanced Level)1025.PAT Ranking

    To evaluate the performance of our first year CS majored students, we consider their grades of three ...

  8. HIVE udf实例

    本例中udf来自<hive编程指南>其中13章自定义函数中一个例子. 按照步骤,第一步,建立一个项目,创建 GenericUDFNvl 类. /** * 不能接受第一个参数为null的情况 ...

  9. C++ 包含目录、库目录、附加包含目录、附加库目录、附加依赖项之详解(转)

    最近因为接触机器学习,所有涉猎到C++方面的开发.在c++中有几个概念很迷糊. VS项目中的包含目录.库目录.附加包含目录.附加库目录.附加依赖项均在"项目->属性->配置属性& ...

  10. 树莓派和STM32通过USB和串口通信记录

    不管怎样,为了简便开发,通信选择串口通信. 推荐文章:https://blog.csdn.net/magnetoooo/article/details/53564797 推荐测试工具:https:// ...