LeetCode题库整理(自学整理)

1. Two Sum 两数之和       来源:力扣(LeetCode)
题目:给定一个整数数组和一个目标值,找出数组中和为目标值的两个数。你可以假设每个输入只对应一种答案,且同样的元素不能被重复利用。
示例: 给定 nums = [2, 7, 11, 15], target = 9    因为 nums[0] + nums[1] = 2 + 7 = 9   所以返回 [0, 1]
这道题目比较容易想到的是通过暴力搜索求解,但暴力搜索的时间复杂度为 O(n^2)。如果使用哈希的思想,利用Python中list的查询方式,我们可以将复杂度降低到 O(n)。有两个值得注意的地方:
(1). 同样的元素不能重复使用(也就是不能自己加自己)    (2). 给定的数组中可能有相同的元素(比如 [3, 3, 4, 4, 5])
java代码:

 

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

HashMap是Java中集合的一部分。它提供了Java的Map接口的基本实现。它将数据存储在(Key,Value)对中。


python代码:
class Solution:

    def twoSum(self, nums: List[int], target: int) -> List[int]:

        numsMap = {}
        for index,num in enumerate(nums):
            tmpDiff = target-num
            if tmpDiff in numsMap.keys():
                return [numsMap[tmpDiff],index]
            numsMap[num] = index
        return None 

 

posted @ 2019-09-09 10:43  张继123  阅读(6733)  评论(0编辑  收藏  举报