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

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

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/two-sum

方法一:暴力枚举

遍历数组中的的每一个x,寻找是否存在target-x。

由于每一个位于x之前的元素都与x匹配过,因此每次遍历只需从x之后的元素开始寻找target-x。

代码:

public class Test_1_1 {
public static void main(String[] args) {
int nums[]=new int[]{4,7,1,9,6};
int target=8;
int twoSum[]= Test_1_1.twoSum(nums,target);
//测试
for (int i:twoSum){
System.out.println(i);
}
}
public static int[] twoSum(int[] nums, int target) {
//定义返回的索引数组
int twoindex[]=new int[2];
//遍历前length-1个元素,寻找后面是否有与之匹配的元素
for (int i=0;i<nums.length-1;i++){
//只需从nums[i]之后寻找
for (int j=i+1;j<nums.length;j++){
//若匹配到则存储索引下标
if (nums[i]+nums[j]==target){
twoindex[0]=i;
twoindex[1]=j;
}
}
}
return twoindex;
}
}

运行结果:

方法二:哈希表查找

遍历数组中每一个x元素,先在哈希表中查找是否存在key值为target-x,如果没有,则将x作为key值,索引作为value存入哈希表中,方便后续查找;如果有,则取出相应的value值。

代码:

public class Test_1_2 {
public static void main(String[] args) {
int nums[]=new int[]{8,0,9,1,8,7};
int target=10;
int a[]=Test_1_2.twoSum(nums,target);
//测试
for (int i:a){
System.out.println(i);
} }
public static int[] twoSum(int[] nums, int target) {
int num[]=new int[2];
//定义哈希表
Map<Integer,Integer> map=new HashMap<>();
//遍历每一个x元素
for (int i=0;i<nums.length;i++){
int j=target-nums[i];
//若在map中找到与x匹配的值,则取出索引
if (map.containsKey(j)){
num[1]=i;
num[0]=map.get(j);
}
//没有则将x作为key值存入map中
else {
map.put(nums[i],i );
}
}
return num;
}
}

运行结果:

leetcode_两数之和的更多相关文章

  1. LeetCode_#1_两数之和 Two Sum_C++题解

    1. 两数之和 Two Sum 题目描述 Given an array of integers, return indices of the two numbers such that they ad ...

  2. 给定数组A,大小为n,现给定数X,判断A中是否存在两数之和等于X

    题目:给定数组A,大小为n,现给定数X,判断A中是否存在两数之和等于X 思路一: 1,先采用归并排序对这个数组排序, 2,然后寻找相邻<k,i>的两数之和sum,找到恰好sum>x的 ...

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

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

  4. 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 ...

  5. LeetCode 167. Two Sum II - Input array is sorted (两数之和之二 - 输入的是有序数组)

    Given an array of integers that is already sorted in ascending order, find two numbers such that the ...

  6. [LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树

    Given a Binary Search Tree and a target number, return true if there exist two elements in the BST s ...

  7. [LeetCode] 1. Two Sum 两数之和

    Part 1. 题目描述 (easy) Given an array of integers, return indices of the two numbers such that they add ...

  8. Leetcode(一)两数之和

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

  9. 南大算法设计与分析课程OJ答案代码(1)中位数附近2k+1个数、任意两数之和是否等于给定数

    问题1 用来测试的,就不说了 问题2:中位数附近2k+1个数 给出一串整型数 a1,a2,...,an 以及一个较小的常数 k,找出这串数的中位数 m 和最接近 m 的小于等于 m 的 k 个数,以及 ...

随机推荐

  1. window 消息传递机制【复杂版本】

    一.消息概述     众人周知,window系统是一个消息驱动的系统, windows操作系统本身有自己的消息队列称做系统消息队列(操作系统队列),消息循环,它捕捉键盘,鼠标的动作生成消息,并将这个消 ...

  2. .大内高手专栏: NET中间语言(IL)

    补充知识点:opcode 在前面我们已经知道了,由于计算机只认识0和1,所以,源代码"NOP"是无法直接运行的.当Assembler遇到"NOP"的时候,为了生 ...

  3. 使用linux 的shell脚本进行sftp文件上传与下载

    一.批量上传: #!/bin/bash #SFTP配置信息 #用户名 USER=root #密码 PASSWORD=5EYS40T04BMF #待上传文件根目录 SRCDIR=/u02/dab/sft ...

  4. Java课程设计---WindowBuilder插件安装

    1 .获取插件地址 WindowBuilder 地址http://www.eclipse.org/windowbuilder/download.php 打开网址后会看到如下 2.在线方式安装插件 根据 ...

  5. Python:numpy

    学习自:NumPy 教程 | 菜鸟教程 官网:Numpy官方文档 1.简介 numpy主要用于数组计算,包含: 1)一个强大的N维数组对象ndarray 2)广播功能函数 3)整合 C/C++/For ...

  6. Vue-router路由判断页面是否登录,未登录跳转到登录页面

    在index.js中 //定义路由 const router = new Router({ routes, strict: process.env.NODE_ENV !== 'production', ...

  7. jq 简易购物车功能实现

    <!DOCTYPE html><html> <head> <meta charset="utf-8"> <title>& ...

  8. MySQL配置主从分离

    主服务器 192.168.176.110 从服务器 192.168.176.120 主数据库操作(ip:192.168.176.110)  配置MySQL主服务器的配置文件 [root@localho ...

  9. FatFs知识点总结[多篇转载]

    一.实用简单的fatfs基础知识点总结: https://my.oschina.net/u/274829/blog/282135 二.深入点的FAT表解析: http://blog.chinaunix ...

  10. redis不重启,切换到RDB备份到AOF备份

    redis不重启,切换RDB备份到AOF备份 确保redis版本在2.2以上 查看redis版本 redis-server -v 实验环境准备 本文是在redis4.0中,通过config set命令 ...