1.两数之和

题目:给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。

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

方法一:暴力求解

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int n = nums.length;
        for (int i = 0; i < nums.length-1; ++i) {
            for (int j = i + 1; j < nums.length; ++j) {
                //如果j用1开始的话,容易和i重复
                if (nums[i] + nums[j] == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }
}

方法二:哈希表
在遍历的同时,记录一些信息,以省去一些循环,以空间换时间的想法。需要记录已遍历的数值和它所对应的下标。


图片.png

target是8,6在之前没有元素2与之对应,所以放入hash表中,value为0,3在之前没有元素5与之对应,所以放入hash表中,value为1,8在之前没有元素0与之对应,所以放入hash表中,value为2,2在于之前的6所对应,所以输出[0,3]。

    public int[] twoSum(int[] nums, int target) {
        //初始化哈希表的时候尽量指定哈希表的容量,以避免哈希表扩容所带来的性能消耗
        Map<Integer, Integer> hashtable = new HashMap<Integer, Integer>(nums.length -1);
        //由于在第一个元素之前一定没有其他元素与之对应,因此直接放入hash表中
        hashMap.put(num[0],0);
        //从下标为1的第一个元素开始遍历
        for (int i = 1; i < nums.length; ++i) {
            //每次之前都需要检查在它之前是否有对应的元素在不在哈希表中
            if (hashtable.containsKey(target - nums[i])) {
                return new int[]{hashtable.get(target - nums[i]), i};
            }
            hashMap.put(num[i],i);
        }
        return new int[0];
    }
}
class Solution {
    public int[] twoSum(int[] nums, int target) {
      Map<Integer,Integer> hasmap = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (hasmap.containsKey(target-nums[i])){
                return new int[]{hasmap.get(target-nums[i]),i};
            }
            hasmap.put(nums[i],i);
        }
        return new int[0];
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 题目 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 的那两个整数,并返...
    陶特斯阅读 174评论 0 0
  • 1.两数之和 给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样...
    Gunther17阅读 1,062评论 2 6
  • 题目描述 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那两个整数,并返回...
    辰绯阅读 143评论 0 0
  • 题目描述:给定一个整数数组 nums 和一个整数目标值 target ,请你在该数组中找出 和为目标值 targe...
    Zy_0818阅读 461评论 0 5
  • 题目 分析 这道题目给我们一个数组,数组里面全是整数,然后再给我们一个数字 target,需要我们求出在这个数组中...
    zzpwestlife阅读 360评论 1 2