leetcode(Two Sum)

Title:Two Sum     1

Difficulty:Easy

原题leetcode地址:https://leetcode.com/problems/two-sum/

 

下面主要是3种解法:

1. 暴力法,时间&空间复杂度如下:

时间复杂度:O(n^2),两层for循环,每一层for循环再没有找到对应的target时,都是要执行n次。

空间复杂度:O(1),申请了一维长度为2数组。

    /**
     * 暴力法
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum(int[] nums, int target) {
        int index[] = new int[]{0, 1};

        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; i < nums.length; j++) {
                if (target == nums[i] + nums[j]) {
                    index[0] = i;
                    index[1] = j;
                }
            }
        }

        return index;
    }

2. 采用Set集合的唯一性,时间&空间复杂度如下:

时间复杂度:O(n),虽然代码中包含了两层for循环,但是不是在第一层时,第二层每次都需要执行一次for循环。

空间复杂度:O(n),申请了HashSet,最长为n。

    /**
     * 利用Set集合的唯一性
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum2(int[] nums, int target) {
        int index[] = new int[]{0, 1};
        Set hset = new HashSet();

        for (int i = 0 ; i < nums.length; i++) {
            if (hset.add(target - nums[i])) {
                hset.remove(target - nums[i]);
                hset.add(nums[i]);
            } else {
                index[1] = i;
                for (int j = 0; j < i; j++) {
                    if (target == (nums[i] + nums[j])) {
                        index[0] = j;
                    }
                }
            }
        }

        return index;
    }

3. 采用Map的Key的唯一性,时间&空间复杂度如下:

时间复杂度:O(n),一层for循环,最长遍历时数据的长度。

空间复杂度:O(n),申请了HashMap,最长为n。

    /**
     * 利用Map的Key唯一性
     * @param nums
     * @param target
     * @return
     */
    public static int[] twoSum3(int[] nums, int target) {
        int index[] = new int[]{0, 1};
        Map<Integer, Integer> hmap = new HashMap<Integer, Integer>();

        for (int i = 0; i < nums.length; i++) {
            if (hmap.containsKey(target - nums[i])) {
                index[0] = hmap.get(target - nums[i]);
                index[1] = i;
            }
            hmap.put(nums[i], i);
        }

        return index;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鬼王呵

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值