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;
    }
}
相关推荐
彧azz20 分钟前
Java学习记录:判断语句
java·笔记·学习·算法
alphaTao24 分钟前
LeetCode 每日一题 2026/9/14-2026/9/20
算法·leetcode
hanlin0326 分钟前
刷题笔记:力扣第560题-和为k的子数组
笔记·算法·leetcode
residual_fan42 分钟前
航空发动机故障诊断专用智能体(四):深度强化学习与自适应奖励机制
人工智能·算法·数据挖掘·数据分析
2601_9622186143 分钟前
万象生鲜系统多终端统一数据协议PC手机PDA数据实时同步
大数据·数据库·人工智能·python·算法
AgentMaster43 分钟前
企业元数据管理技术实战:从采集架构到血缘解析的完整方案
大数据·人工智能·算法
晴天的雨.9921 小时前
[C++算法]盛最多水的容器(双指针算法)
开发语言·c++·算法
顶点多余2 小时前
9.16 面试总结
linux·面试·职场和发展
不会就选b2 小时前
算法日常・每日刷题--<贪心>15
算法
鹿角片ljp2 小时前
Prompt Cache、Token 成本与 Plan Compiler 的工程设计
java·python·算法