LeetCode之Two Sum

霍金昨天回到了属于他的宇宙星空,他本不属于这里,他属于宇宙

前言,准备开始看LeetCode,不知道什么时候能看完,但是有什么关系呢?有时候做一些事,只是为了兴趣而已,何必要把自己搞的那么辛苦,那么信誓旦旦。

LeetCode官网:https://leetcode.com/

我是直接用GitHub授权登录的。

问题

给定一个整数数组,返回这两个数字的索引,使它们合计成一个特定的目标。

举例

Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

解法一(不经思考,暴力解决)

public int[] twoSum(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        for (int j = i + 1; j < nums.length; j++) {
            if (nums[j] == target - nums[i]) {
                return new int[] { i, j };
            }
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

时间复杂度:O(n^2)
空间复杂度:O(1)

解法二(双向哈希表)

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

时间复杂度:O(n)
空间复杂度:O(n)

解法三(一次散列表)

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

时间复杂度:O(n)
空间复杂度:O(n)

测试用例

具体解法代码,建议不借助IDE手写

public class TwoSum {

    public static void main(String[] args) {
        //学习两种声明数组的方式
        int[] nums = new int[]{2, 7, 11, 15};
        int[] num = {2, 71, 11, 15, 7};
        int target = 9;
        int[] arr = twoSum(num, target);
        System.out.println(Arrays.toString(arr));
    }

    public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (map.containsKey(complement)) {
                return new int[] { map.get(complement), i };
            }
            map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No two sum solution");
    }
}

借用知乎的一首打油诗

明有科举八股,
今有leetcode。
leetcode定题目且重答案背诵。
美其名曰:“practice makes perfect.”
为何今不如古?
非也非也,
科举为国取士,
leetcode为Google筛码工,
各取所需也。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值