0001

1. 两数之和

题目

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

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

示例1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 

示例2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

题目大意

在数组中找到2个数之和等于给定的值,结果返回2个数字在数组中的下标。

方法一:暴力枚举

思路及算法

枚举数组中的每一个数 x ,寻找数组中是否存在 target - x

class Solution {
    public int[] twoSum(int[] nums, int target) {

        int n = nums.length;
        for(int i=0;i<n;i++){
            for(int j=i+1; j<n; j++){
                if(nums[i]+nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return new int[0];
    }
}

复杂度分析

  • 时间复杂度:O(N^2)
  • 空间复杂度:O(1)

方法二:哈希表

思路及算法

顺序扫描数组,对每一个元素,在map中找到能组合给定值的另一半数字,如果找到了,直接返回2个数字的下标即可。如果找不到,就把这个数字存入map中,等待扫到 ”另一半“数字的时候,再取出来返回结果。

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

复杂度分析

  • 时间复杂度:O(N),其中N是数组中的元素数量。对于每一个元素 x , 我们可以O(1)地寻找target - x。
  • 空间复杂度:O(N),其中N是数组中的元素数量。主要为哈希表的开销。

posted @ 2022-03-28 12:35  爱睡觉的卡比兽  阅读(285)  评论(0)    收藏  举报