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;
    }
}
相关推荐
mCell6 小时前
Lua 编程入门:从基础语法到元表
javascript·算法·lua
wuyk5558 小时前
98.C语言易混难点:字符数组与字符串指针的底层差异
c语言·开发语言·c++·stm32·嵌入式硬件·算法
峥无8 小时前
从0到1手撕红黑树:封装实现 my_map 与 my_set(SGI-STL 源码级深度解析)
开发语言·c++·笔记·算法·stl
不会代码的小猴9 小时前
3. 控件学习1
开发语言·c++·笔记·qt·算法
碳基猿9 小时前
案例|普通内容创作者如何利用 CreBee 打造个人内容创业系统:从一个账号到多平台内容资产矩阵
职场和发展·新媒体运营·创业创新·程序员创富·新媒体矩阵
203号居民11 小时前
LeetCode hot 100 —41. 缺失的第一个正数
数据结构·算法·leetcode
专注仿真13 小时前
问答大模型技术方案算法实现-熵权法融合算法 + 交叉编码器重排算法
人工智能·python·算法·语言模型·问答大模型关键算法·熵权融合算法·交叉编码器重排算法
evans在进步13 小时前
LeetCode 322:零钱兑换——Java 动态规划详解
java·leetcode·动态规划
地平线开发者14 小时前
量化为什么会有损失:从量化误差到精度下降
算法