Day07-06_13【CT】LeetCode手撕—1. 两数之和

目录

  • 题目
  • 1-思路
  • [2- 实现](#2- 实现)
    • [⭐1. 两数之和------题解思路](#⭐1. 两数之和——题解思路)
  • [3- ACM实现](#3- ACM实现)

题目


1-思路

哈希表

  • 利用哈希表存储 key 数组元素值 ------> value 数组下标
  • 遍历数组

2- 实现

⭐1. 两数之和------题解思路

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];

        // 哈希表
        Map<Integer,Integer> map = new HashMap<>();
        // 存 key 值 ------> value 下标


        // 遍历数组
        for(int i  = 0 ; i < nums.length ;i++){
            if(map.containsKey(target-nums[i])){
                res[0] = i;
                res[1] = map.get(target-nums[i]);
            }
            map.put(nums[i],i);
        }
        return res;
    }
}

3- ACM实现

java 复制代码
public class twoSum {

    public static int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];

        // 哈希表
        Map<Integer,Integer> map = new HashMap<>();
        // 存 key 值 ------> value 下标


        // 遍历数组
        for(int i  = 0 ; i < nums.length ;i++){
            if(map.containsKey(target-nums[i])){
                res[0] = i;
                res[1] = map.get(target-nums[i]);
            }
            map.put(nums[i],i);
        }
        return res;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("输入数组长度");
        int n = sc.nextInt();
        int[] nums = new int[n];
        for(int i = 0 ; i < n;i++){
            nums[i] = sc.nextInt();
        }
        System.out.println("输入目标和");
        int target = sc.nextInt();
        int[] forRes = twoSum(nums,target);
        for(int i : forRes){
            System.out.print(i+" ");
        }
    }
}
相关推荐
Jayden_Ruan15 小时前
C++逆向输出一个字符串(三)
开发语言·c++·算法
点云SLAM16 小时前
C++ 常见面试题汇总
java·开发语言·c++·算法·面试·内存管理
叙白冲冲16 小时前
哈希算法以及面试答法
算法·面试·哈希算法
YuTaoShao17 小时前
【LeetCode 每日一题】1277. 统计全为 1 的正方形子矩阵
算法·leetcode·矩阵
古译汉书17 小时前
嵌入式铁头山羊stm32-ADC实现定时器触发的注入序列的单通道转换-Day26
开发语言·数据结构·stm32·单片机·嵌入式硬件·算法
野犬寒鸦17 小时前
力扣hot100:相交链表与反转链表详细思路讲解(160,206)
java·数据结构·后端·算法·leetcode
阿昭L17 小时前
leetcode两数之和
算法·leetcode
周树皮不皮17 小时前
【Leetcode100】算法模板之二叉树
算法
无名客017 小时前
sentinel限流常见的几种算法以及优缺点
算法·sentinel·限流
Lris-KK18 小时前
【Leetcode】高频SQL基础题--1164.指定日期的产品价格
sql·leetcode