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+" ");
        }
    }
}
相关推荐
kyle~1 小时前
OpenCV---特征检测算法(ORB,Oriented FAST and Rotated BRIEF)
人工智能·opencv·算法
初学小刘1 小时前
决策树:机器学习中的强大工具
算法·决策树·机器学习
山顶风景独好1 小时前
【Leetcode】随笔
数据结构·算法·leetcode
lxmyzzs3 小时前
【图像算法 - 16】庖丁解牛:基于YOLO12与OpenCV的车辆部件级实例分割实战(附完整代码)
人工智能·深度学习·opencv·算法·yolo·计算机视觉·实例分割
wow_DG3 小时前
【C++✨】多种 C++ 解法固定宽度右对齐输出(每个数占 8 列)
开发语言·c++·算法
Epiphany.5563 小时前
c++最长上升子序列长度
c++·算法·图论
Cx330❀4 小时前
【数据结构初阶】--排序(四):归并排序
c语言·开发语言·数据结构·算法·排序算法
余_弦4 小时前
区块链中的密码学 —— 密钥派生算法
算法·区块链
亲爱的非洲野猪5 小时前
令牌桶(Token Bucket)和漏桶(Leaky Bucket)细节对比
网络·算法·限流·服务
NAGNIP5 小时前
一文读懂LLAMA
算法