版权声明:本文章为博主原创,转载请注明出处。保留所有权利。

Contents
  1. 1. 题目
  2. 2. 解析

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.

    1
    2
    3
    4
    Example:
    Given nums = [2, 7, 11, 15], target = 9,
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
  • 解析

      在给定的数组里面找到两个和为给定值的元素的下标,题目里已经说明给定的数组有唯一解,直接暴搜了(其实应该用hash table类的方法)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    class Solution(object):
    def twoSum(self, nums, target):
    """
    :type nums: List[int]
    :type target: int
    :rtype: List[int]
    """
    i=0

    for num1 in nums:
    j =i+1
    for num2 in nums[j:]:
    if num1+num2 == target :
    return [i,j]
    j+=1
    i+=1

打赏

取消
扫码支持

你的支持是对我最好的鼓励

Contents
  1. 1. 题目
  2. 2. 解析