【LeetCode题解---1】Two Sum.md

【LeetCode题解—1】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].
    地址 https://oj.leetcode.com/problems/two-sum/ 
    

词汇

integers 整数 indices 指数 add up 加起来

specific 具体 target 目标 assume 承担

exactly 究竟 solution 解 解答

翻译

​ 给定一个整数数组 一个目标整数 求出这个整数值是数据中的哪两个元素的和 返回下标组成的数组

解法-Java

解法一

暴力搜索解法:暴力搜索的方法是遍历所有的两个数字的组合,然后算其和。

public static int[] twoSum(int[] nums, int target) {
        int[] array = new int[2];
        for (int i=0;i<nums.length;i++) {
            for (int j=1;j<nums.length - 1;j++) {
                if (nums[i] + nums[j] == target) {
                    array[0] = i;
                    array[1] = j;
                    break;
                }
            }
        }
        return array;
    }

解法二

遍历一个数字,那么另一个数字呢,我们可以事先将其存储起来,使用一个HashMap,来建立数字和其坐标位置之间的映射,我们都知道HashMap是常数级的查找效率,这样,我们在遍历数组的时候,用target减去遍历到的数字,就是另一个需要的数字了,直接在HashMap中查找其是否存在即可,注意要判断查找到的数字不是第一个数字,比如target是4,遍历到了一个2,那么另外一个2不能是之前那个2,整个实现步骤为:先遍历一遍数组,建立HashMap映射,然后再遍历一遍,开始查找,找到则记录index。

public static int[] twoSum2(int[] nums,int target) {
    int[] array = new int[2];
    for (int i=0;i<nums.length;i++) {
        map.put(nums[i],i);
    }
    for (int i=0;i<nums.length;i++) {
        if (map.containsKey(temp) && map.get(temp) != nums[i]) {
            array[0] = i;
            array[1] = map.get(temp);
            break;
        }
    }
    return array;
}

解法三

结题思路同解法2 但是可以爸两个for循环做合并 使得代码更加简洁


解法-Python

解法一

同上述java版本暴力解法一致,直接使用for循环


此方法循环时间都很长: 按照官方代码来说,还是采用字典更好

解法二

采用字典方式进行计算

class Solution:
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        #创建字典一:存入nums[i],i
        num_dict={num[i]: i fori in range(len(nums))}
        #创建字典二:存入i:target-nums[i]
        num_dict2={i:target-num[i] fori in range(len(nums))}
 
        towSum=[]
        for i in range(len(nums)):
            j=num_dict.get(num_dict2.get(i))
            if (j is not None) and (j!=i):
                towSum=[i,j]
                break
        return towSum

以上代码会同步更新在本人的Github和CSDN上

Github地址:https://github.com/Bylant/LeetCode

CSDN地址:https://blog.csdn.net/ZBylant
微信公众号 【LeetCode题解---1】Two Sum.md_第1张图片

你可能感兴趣的:(LeetCode)