leetcode 1

Posted 玉树临风獾獾欢

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 1相关的知识,希望对你有一定的参考价值。

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].

 Solution_1

简单的for语句

class Solution(object):
    def twoSum(self, nums, target):
        """
        :type nums: List[int]
        :type target: int
        :rtype: List[int]
        """
        for index1, num1 in enumerate(nums):
            for index2, num2 in enumerate(nums):
                if index1 != index2:
                    if num1 + num2 == target:
                        return [index1, index2]

Solution_2

用一个字典来表示每个索引和target之间的差。然后判断列表中的元素是否在字典的键值中

class Solution(object):
    def twoSum(self, nums, target):
        if len(nums) <= 1:
            return False
        buff_dict = {}
        for i in range(len(nums)):
            if nums[i] in buff_dict:
                return [buff_dict[nums[i]], i]
            else:
                buff_dict[target - nums[i]] = i

 

以上是关于leetcode 1的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 763 划分字母区间

LeetCode:划分字母区间763

Leetcode.1024 视频拼接

LEETCODE 003 找出一个字符串中最长的无重复片段

Leetcode:Task Scheduler分析和实现

817. Linked List Components - LeetCode