LeetCode 一 two Sum 笔记

# 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.

Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[ 1 ] = 2 + 7 = 9,
return [0, 1].
给你一个数组和一个目标数,寻找数组中两个数相加为目标数,返回这两个数组成的数组
一般思路为两重循环取两个数相加为target的

    class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        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;
                }
        }
    }
    return result;
}

可以看出该算法有两重for循环 算法复杂度为O(n^2)
有没有更简单的算法呢 ?可以看出两重for循环扫了很多重复的数据,如果能够把扫过的数据存储起来,是不是可以降低复杂度呢?
如果要存储的话,存储在哪里好呢。存储在list? 似乎并没有什么变化。map? 有啥用呢?如果一个map的key-value 相加为target 扫描后面的数组是看是否有重复是不是就好了呢?

class Solution {
    public int[] twoSum(int[] nums, int target) {
        //定义返回数组
        int[] result = new int[2];
        //定义一个map
        Map<Integer,Integer> map = new HashMap<Integer,Integer>();
        for (int i=0;i<nums.length;i++){
            if(map.containsKey(target-nums[i])){
                //result[0]是之前存进去的key对应的value
                result[0]=map.get(target-nums[i]);
                //result[1]肯定是当前的i
                result[1]=i;
                break;  
            }else{
                //扫过一遍之后存进去
                map.put(nums[i],i);
            }   
        }
        return result;
    }
}
class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        dict = {}
        for i in range(len(nums)):
            if dict.get(target-nums[i],None)==None:
                dict[nums[i]]=i
            else :
                return (dict[target - nums[i]], i )

看了一眼正确答案 还好是用java写的

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

抛异常也有 而且代码也简洁

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值