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+" ");
        }
    }
}
相关推荐
量化君也几秒前
桥水基金全天候策略拆解,构建中国ETF躺平版策略
大数据·人工智能·python·算法·金融·业界资讯
蓦然回首却已人去楼空9 分钟前
画图专用文档
算法
洛水水11 分钟前
【力扣100题】78.在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·leetcode
江屿风12 分钟前
C++图论基础拓扑排序算法流食般投喂
开发语言·c++·笔记·算法·排序算法
海棠AI实验室19 分钟前
AI 时代文献综述:从检索到成稿的 RAG 五步法
windows·算法·自动化·llm·rag
H1785350909619 分钟前
SolidWorks_基于草图的实体特征14_扫描扭转与控制
前端·人工智能·算法·3d建模·solidworks
黄金龙PLUS22 分钟前
基于ARX结构的新型序列密码算法FlashLight
算法·网络安全·密码学·哈希算法·同态加密
洛水水26 分钟前
【力扣100题】77.搜索二维矩阵
算法·leetcode·矩阵
仙俊红37 分钟前
深入理解 ThreadLocal —— 从变量引用、强弱引用到 Spring Boot 实战
spring boot·python·算法
故渊at40 分钟前
第五板块:Android 系统服务与电源管理 | 第十八篇:Battery Service 与 电量统计(Fuel Gauge)算法
android·算法·battery·电源·电池·电源管理·电量统计