LeetCode系列之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.

我来翻译一下:也就是给一个数组和一个两数的和,让你从这个数组中找到两个数加起来等于这个和,给出在数组中的位置

注意下一句才是重点:假设一组输入中有且只有一组满足这个条件,并且给的数组没有重复的元素

思考:
  1. 当然是按个遍历一遍,也就是类似于倒三角样式的遍历,复杂度n*n
for(int i = 0;i < nums.length;i++){
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    break;
                }
            }
        }
2.思考题目中最后一句话能发现一些玄机,只有一组满足条件,并且没有重复元素,这句话就是告诉我们只用遍历一次就能得出结论,在看了别人的优解之后还是挺佩服的
 Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < numbers.length; i++) {
        if (map.containsKey(target - numbers[i])) {
            result[1] = i + 1;
            result[0] = map.get(target - numbers[i]);
            return result;
        }
        map.put(numbers[i], i + 1);
    }
  • 利用map存储key的hash特性使得找key的复杂度是常数
  • 利用没有重复元素使得key值唯一
  • 利用只有一组解大胆return,不继续剩下的元素

大神解法链接:leetcode:two sum,id:jiaming2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值