LeetCode 1. 两数之和

1. Two Sum

Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

You may assume that each input would have exactly one solution, and you may not use the same element twice.

You can return the answer in any order.

Example 1:

**Input:**nums = 2,7,11,15, target = 9

Output: 0,1

Explanation: Because nums0 + nums1 == 9, we return 0, 1.

Example 2:

**Input:**nums = 3,2,4, target = 6

Output:1,2

Example 3:

**Input:**nums = 3,3, target = 6

Output: 0,1

Constraints:

  • 2 <= nums.length <= 10^4
  • -10^9 <= numsi <= 10^9
  • -10^9 <= target <= 10^9

Only one valid answer exists.

Follow-up: Can you come up with an algorithm that is less than O(n2) time complexity?

解法思路:

1、暴力求解

2、利用map集合的特性

java 复制代码
class Solution {
    public int[] twoSum(int[] nums, int target) {
        // 暴力求解,O(n^2)
        // int[] res = new int[2];
        // for (int i = 0; i < nums.length - 1; i++) {
        //     for (int j = i + 1; j < nums.length; j++) {
        //         if (nums[i] + nums[j] == target) {
        //             res[0] = i;
        //             res[1] = j;
        //             return res;
        //         }
        //     }
        // }
        // return new int[0];

        // O(n)
        // Map<Integer, Integer> map = new HashMap<>();
        // int[] res = new int[2];
        // for (int i = 0; i < nums.length; i++) {
        //     int anotherNum = target - nums[i];
        //     if (map.containsKey(anotherNum)) {
        //         res[0] = map.get(anotherNum);
        //         res[1] = i;
        //         return res;
        //     }
        //     map.put(nums[i], i);
        // }
        // return new int[0];

        // 优化下
        Map<Integer, Integer> map = new HashMap<>();
        int n = nums.length;
        for (int i = 0; i < n; i++) {
            int anotherNum = target - nums[i];
            if (map.containsKey(anotherNum)) {
                return new int[]{map.get(anotherNum), i};
            } else {
                map.put(nums[i], i);
            }
        }
        return null;
    }
}
相关推荐
浩哥学JavaAI7 小时前
2026年最新AI agent面试(10)_通信与行业动态
人工智能·面试·职场和发展
可编程芯片开发8 小时前
基于MATLAB的PEF湍流风场生成器模拟与仿真
算法
罗西的思考8 小时前
【Agentic RL / 强化学习 / OPD】OpenClaw-RL 源码阅读笔记 --- (9)--- Reward Judging
人工智能·算法·机器学习
Mr.HeBoYan10 小时前
一次持续三天才出现的丢包故障——深入解析 DPDK Memory Ordering、rte_ring 与 CPU Memory Barrier (下)
linux·网络·算法·架构·dpdk
wabs66610 小时前
关于图论【深度优先搜索的理论基础】
算法·深度优先·图论
先吃饱再说11 小时前
LeetCode 101. 对称二叉树
算法
是Dream呀12 小时前
人眼看不出的伪造,AI如何识别?实测合合信息跨模态鉴伪与去反光技术
算法
QN1幻化引擎12 小时前
SFA 信号场注意力:用8KB参数换248x KV Cache压缩,边缘设备也能跑长序列
人工智能·算法·gitee·gitlab
段一凡-华北理工大学12 小时前
向量数据库实战:选型、调优与落地~系列文章03:向量相似度算法全解:余弦、欧氏、内积,到底该用哪个?
大数据·数据库·人工智能·算法·机器学习·向量相似度·高炉炼铁
cjr_xyi14 小时前
AT1202Contest_c binarydigit 题解
c语言·c++·算法