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, and you may not use the same element twice.

Example

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

思路分析

1、暴力法(O( n2 ))
这种方式比较简单,两层循环。外层循环确定一个num[i],然后内层循环判断num[j]==target-num[i],如果为true就得到了结果。
时间复杂度为O( n2 )
2、借助HashMap
数据结构中,数组寻址方便,通过下标就可以直接得到值,但是插入和删除比较困难。如果是直接在末尾插入,操作方便,但也存在数组越界的可能,需要检查数组容量并在超出范围后进行手动扩容,同时如果在中间进行插入,要依次向后移动数组元素,空出一个位置供新元素写入;而删除元素,则要把后面的元素依次向前移。对于链表,则是插入和删除简单,只需要修改指针,无需移动元素。但是访问时比较费时,比如对于单向链表,必须要从头节点开始遍历。
HashMap结合和数组和链表的优点,采用了数组和链表的组合方式,因此也叫“链表散列”。插入元素时,由key值通过hashcode找到对应数组的位置,放入横向数组的某个格子中。因为前面说到hashcode值不能保证唯一,即不同的key值会对应同一个数组下标,发生碰撞。如果之后hashcode值对应的数组位置中已经有值,就放到相连的链表中。查找元素也是按这个过程来进行。

利用HashMap我们可以一次遍历就能得到结果。当我们迭代并将元素插入到hashmap中时,我们还会回过头来检查当前元素的补充是否已经存在于hashmap中。如果它存在,我们就找到了一个解决方案并立即返回。

代码

public static int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            int res = target - nums[i];
            if (map.containsKey(res)) {
                return new int[] { map.get(res), i };
            }
            map.put(nums[i], i);
        }
        return new int[]{0,0};
    }

public static int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if(map.containsKey(nums[i]))
            {
                return new int[]{map.get(nums[i]),i};
            }else
            {
                map.put(target-nums[i], i);
            }
        }
        return new int[]{0,0};
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值