Leetcode旅途一

No.1:Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:

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

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

初见思想方法:

在一个给定的整数数组中,找出两个不同元素的和为给定目标整数,返回一个数组,数组内存有这两个不同元素的下标位置。

容易想到的方法是两层for循环,遍历查询数组,通过加运算是否符合条件。易得,该算法时间复杂度为O(n^2)。

实现代码如下:


    public int[] twoSum(int[] nums, int target) {
        int[] a = new int [2];
        boolean flag = false;
        for(int i = 0; i < nums.length; i++){
        if(flag) break;
            for(int j = 0; j < nums.length; j++){
            if(flag) break;
                if(nums[i] + nums[j] == target){
                    a[0] = i;
                    a[1] = j;
                    flag = true;
                }
            }
        }
        return a;
    }


但时间代价较大,对于nums数组规模较大的时候,效率显得较慢。


改进方法:

为什么上述方法效率较低,主要是做了两层嵌套遍历,因此效率较低。因此可以通过减少遍历的次数,来提供算法的效率。

在数组中查找相应元素,需要对数组进行遍历来查询,遍历一个n个元素的数组,需要时间复杂度为O(n),而对于哈希表中查询一个元素的时间复杂度则只需O(1)。

因此我们可以考虑使用哈希表能替代数组。

再者,寻找符合要求的这两个数,可以转化为对于已知的一个数,目标数和它的差(即为第二个数)是否存在于哈希表中,利用了哈希表键值对的优点,进而优化效率。

具体实现代码如下:

    public int[] twoSum(int[] nums, int target) {
        int[] a = new int [2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < nums.length; i++){
        Integer n = map.get(nums[i]);
        if(n == null) 
        map.put(nums[i], i);
        n = map.get(target - nums[i]);
        if( n != null && n < i){
        a[0] = n;
        a[1] = i;
        return a;
        }
       
        }
        return a;
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值