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. web题-自己做的

    @sqlmap工具注入 sql基础教程https://jingyan.baidu.com/article/eae078276530621fec5485b9.html 最后啥都有了查询flag表的fla ...

  2. 【VS开发】【C/C++开发】C++参数策略传递内存

    参数策略 如果函数的参数是一个指针,不要指望用该指针去动态申请内存.如下: void GetMemory(char *p, int num) { p = (char *)malloc(sizeof(c ...

  3. 数据结构与算法-queue

    队列和stack类似,stack是先进后出,而queue的先进先出,也是一种特殊的线性表 基本概念 概念 队列是一种特殊的线性表 队列仅在线性表的两端进行操作 队头(Front):取出数据元素的一端 ...

  4. ES6中Set和Map

    1.Set 实例的创建 Set实例它类似于数组,但是成员的值都是唯一的,没有重复的值. Set本身是一个构造函数用来生成Set数据结构. Set 函数可以接受一个数组(或者具有 iterable 接口 ...

  5. jstat 命令

    NAME jstat - Monitors Java Virtual Machine (JVM) statistics. This command is experimental and unsupp ...

  6. ucloud-monitor

    创建报警模板: 可以从现有模板导入: 设定指标: #通知人管理,可以设置报警短信通知人: #给主机绑定告警模板: 勾选要绑定的主机 点设置: #选择要添加的告警模板

  7. SqlException 服务器主体无法在当前安全上下文下访问数据库

    遇到一个错误如下 System.Data.SqlClient.SqlException  HResult=0x80131904  Message=服务器主体 "用户名" 无法在当前 ...

  8. 并不对劲的CF1239B&C&D Programming Task in the Train to Catowice City

    CF1239B The World Is Just a Programming Task 题目描述 定义一个括号序列s是优秀的,当且仅当它是以下几种情况的一种: 1.|s|=0 2.s='('+t+' ...

  9. Codeforces 1244D. Paint the Tree

    传送门 首先如果某个点的度数大于 $2$ 那么显然无解 然后考虑点的度数小于等于 $2$ 的情况 发现其实是一条链 一旦确定了链开头的两个点,后面的点的颜色都可以通过之前的点推出 所以直接枚举即可 # ...

  10. 怎样解决在执行 vue init 时提示 "vue : 无法加载文件" 的问题?

    注意, 以下操作需要 以管理员身份 在 PowerShell 中进行, 不能是 CMD / Git Bash 等. 1. 以 管理员身份 运行 PowerShell 2. 执行 get-Executi ...