Leecode 01 两数之和

404 阅读1分钟

Leecode 01 两数之和

题目:

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。

示例:

给定 nums = [2, 7, 11, 15], target = 9

因为 nums[0] + nums[1] = 2 + 7 = 9 所以返回 [0, 1]

来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum

暴力解法

最简单的暴力解法,每次在数组中取一个数,然后在数组中寻找是否存在另外一个数,加上当前的数等于target,这种解题方法的代码如下:

class solution {
    public int[] twoSum(int[] nums,int target){
        int[] result = new int[2];
        for(int i =0; i < nums.length; i++){
            for(int j = i + 1; j < nums.length; j++){
                if(nums[i]+num[j] == target){
                    result[0] = i;
                    result[1] = j;
                }
            }
        }
  return result;
    }
}

但是这个方法的时间复杂度为(O^2),时间复杂度太高了

HashMap进行优化

从数组中取一个数,然后到Map中查找(target-currentNum)如果能找到,则返回当前数的索引和Map的value,如果取不到值,那么把当前的值作为key,当前值的位置index作为value,存入到Map中。

class solution{
    public int[] twoSum(int[] nums,int target){
        int[] result = new int[2];
        HashMap<Integer,Integer> map = new HashMap<>();
        for(int i =0 ;i <nums.lenght,i++){
            int val = target - nums[i];
            if(map.containsKey(val)){
                result[0] = i;
                result[1] = map.get(val);
                return result;
            }else{
                map.put(nums[i],i);
            }
        }
    }
    return result;
}

启发

使用Map用空间换取时间,算的是比较常规的思路了。

本文使用 mdnice 排版