Leetcode 1. 两数之和(带图)

写下leetCode,每天两道,带上图,题目来源leetCode

题目-1.两数之和(来源:leetCode)

两数之和

在这里插入图片描述
在这里插入图片描述

暴力破解

在这里插入图片描述

代码

    /**
     * 暴力破解
     * @param nums 数组
     * @param target 目标
     * @return
     */
    public static int[] forceCracktwoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < n; ++i) {
            for (int j = i + 1; j < n; ++j) {
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

时间复杂度:O(N^2),其中 N 是数组中的元素数量。最坏情况下数组中任意两个数都要被匹配一次。

空间复杂度:O(1)。

放进map里面比较

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

代码

    /**
     * 放进map里面,相减,判断key值是否包含,不包含,则放进去,包含则返回
     * @param nums
     * @param target
     * @return
     */
    public static int[] mapTwoSum(int[] nums, int target) {
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>();
        for (int i = 0; i < nums.length; ++i) {
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashtable.put(nums[i], i);
        }
        return new int[0];
    }

时间复杂度:O(N),其中 N 是数组中的元素数量。对于每一个元素 x,我们可以 O(1)地寻找 target - x。
空间复杂度:O(N),其中 N 是数组中的元素数量。主要为哈希表的开销。

参考

出处

链接:https://leetcode-cn.com/problems/two-sum/solution/liang-shu-zhi-he-by-leetcode-solution/

参考

https://github.com/MisterBooo/LeetCodeAnimation/tree/master/0001-Two-Sum
  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值