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;
    }
}
相关推荐
CS创新实验室9 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
海石11 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石11 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx11 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie12 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃13 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录14 小时前
prompt-optimizer skill
算法
万法若空14 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时15 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的15 小时前
汇编——内存
开发语言·汇编·算法·网络安全