首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >1. 两数之和

1. 两数之和

作者头像
程序员小航
发布于 2022-01-11 15:28:31
发布于 2022-01-11 15:28:31
5400
举报
文章被收录于专栏:程序员小航程序员小航

题目

题解

暴力枚举

直接遍历出所有的可能性,一一比较。

代码语言:javascript
复制
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int length = nums.length;
        for (int i = 0; i < length - 1; i++) {
            for (int j = i + 1; j < length; j++) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }

        }
        return null;
    }
}

很显然这种方式不会很快,因为双层遍历,时间复杂度为 O(n^2) 。

哈希表

只需要将已经遍历过的值放在 Hash 表中。

K:存放 target - 当前值 V:存放当前 index

这样只需要判断是否在 Hash 表中即可。

代码语言:javascript
复制
class Solution {
    public int[] twoSum(int[] nums, int target) {

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {

            if (map.get(nums[i]) != null) {
                return new int[]{map.get(nums[i]), i};
            }
            map.put(target - nums[i], i);
        }

        return new int[]{-1, -1};
    }
}

- <End /> -

本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2022-01-07,如有侵权请联系 cloudcommunity@tencent.com 删除
目录
  • 题目
  • 题解
    • 暴力枚举
    • 哈希表
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档