码迷,mamicode.com
首页 > 其他好文 > 详细

两数相加LeetCode

时间:2019-06-20 11:15:55      阅读:97      评论:0      收藏:0      [点我收藏+]

标签:不能   整数   ==   get   ++   时间   ash   sum   sla   

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

你可以假设每种输入只会对应一个答案。但是,你不能重复利用这个数组中同样的元素。

示例:

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

因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
/**
     * 无脑暴力:
     * 时间复杂度    :   n^2
     * 空间复杂度    :   1
     * 70ms
     * 38.5MB
     */
    public static int[] traverseTwoSum(int[] nums, int target){
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            for (int j = i+1; j < len; j++) {
                if(nums[i]+nums[j]==target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }
    /**
     * 因为哈希表的查找速度非常的快,我们可以采用hash表去解决问题.
     * 时间: n
     * 空间: n
     *  4ms
     *  36.2MB
     *
     */
    public static int[] secondHashTwoSum(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length;
        for (int i = 0; i < len; i++) {
            // 根据键去找 值
            map.put(nums[i],i);
        }
        int findNum;
        for (int i = 0; i < len; i++) {
            findNum = target - nums[i];
            if(map.containsKey(findNum)&&map.get(findNum)!=i){
                return new int[]{i,map.get(findNum)};
            }
        }
        return null;
    }
    /**
     * 改进为一次hash
     * 时间: n
     * 空间: n
     *  4ms
     *  36.2MB
     *
     */
    public static int[] firstHashTwoSum(int[] nums, int target){
        Map<Integer, Integer> map = new HashMap<>();
        int len = nums.length,findNum;
        for (int i = 0; i < len; i++) {
            findNum = target-nums[i];
            if(map.containsKey(findNum)){
                return new int[] {map.get(findNum),i};
            }
            map.put(nums[i],i);
        }
        return null;
    }

两数相加LeetCode

标签:不能   整数   ==   get   ++   时间   ash   sum   sla   

原文地址:https://www.cnblogs.com/A-FM/p/11057263.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!