1. Two Sum 2019-04-09

https://leetcode.com/problems/two-sum/

Given an array of integers, return indices(index的复数) 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].

先测试,后开发:
测试案例要全面,要充分考虑到边界条件

代码要健壮:
需要考虑到代码执行时会不会出现error、exception,保证代码不会崩溃

代码要优美,可读性要好:
命名要规范,必要的注释需要有

代码要精炼:
充分考虑到程序执行时的时间开销、空间开销

第一步,暴力方法:
Python:

#! /usr/bin/env python
# -*- coding:utf-8 -*-

"""
https://leetcode.com/problems/two-sum/

"""
import os
import sys
PROJECT_PATH = os.path.abspath(os.path.join(sys.path[1], os.pardir))
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        nums_len = len(nums)
        answer_list = []
        for i in range(nums_len):
            is_find = False
            for j in range(i+1, nums_len):
                if j == i:
                    continue
                if nums[i] + nums[j] == target:
                    answer_list.append(i)
                    answer_list.append(j)
                    is_find = True
                    break
            if is_find is True:
                break
        return answer_list
class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        d = {}
        for i,n in enumerate(nums):
           m = target - n
           if m in d:
              return [d[m],i]
           d[n]=i

你可能感兴趣的:(1. Two Sum 2019-04-09)