LeetCode1. 两数之和

题目描述

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 的那两个整数,并返回它们的数组下标。

算法思路

暴力解法:两次遍历,第一次取出nums[i],第二次取出nums[j]并判断nums[i]+nums[j]与target的值是否相等。
哈希表:使用哈希表的containskey()方法避免寻找nums[j]的第二次遍历。
优化哈希表:引入左右指针,避免遍历,时间复杂度优化至最低。

示例代码

暴力解法

class Solution {
    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};
                }
            }
        }
        return new int[0];        
    }
}

时间复杂度:二次遍历,O(n²)
空间复杂度:在不考虑原数组的情况下为O(1)
用时56ms,内存41.2mb

哈希表

class Solution {
    public int[] twoSum(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),哈希表每次定位只花费O(1),共O(n)
空间复杂度:哈希表花费空间O(n),共O(n)
用时1ms,内存41.2mb

引入左右指针

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer , Integer> hashtable = new HashMap<Integer,Integer>();
        int left = 0;
        int right = nums.length - 1;
        while(left <= right) {
            int ln0 = nums[left];
            int rn0 = nums[right];
            int ln1 = target - ln0;
            int rn1 = target - rn0;
            if (hashtable.containsKey(ln1)) {
                return new int[] {left , hashtable.get(ln1)};
            }
            else {
                hashtable.put(ln0 , left++);
            }
            if(hashtable.containsKey(rn1)) {
                return new int[] {right , hashtable.get(rn1)};
            }
             else {
                hashtable.put(rn0 , right--);
            }
        }
        return new int[] {};
    }
}

时空复杂度:同解法二
用时0ms,内存41.5mb

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值