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+" ");
        }
    }
}
相关推荐
独正己身6 分钟前
代码随想录day4
数据结构·c++·算法
利刃大大3 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
Rachela_z4 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@4 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法
追求源于热爱!4 小时前
记5(一元逻辑回归+线性分类器+多元逻辑回归
算法·机器学习·逻辑回归
ElseWhereR4 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法
Smark.4 小时前
Gurobi基础语法之 addConstr, addConstrs, addQConstr, addMQConstr
算法
S-X-S4 小时前
算法总结-数组/字符串
java·数据结构·算法
Joyner20185 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展
因兹菜5 小时前
[LeetCode]day9 203.移除链表元素
算法·leetcode·链表