LeetCode 1. Two Sum
2016-08-27 19:38
369 查看
题目:
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.
Example:
题意:
在数组中返回2个数之和为目标数的下标。
题解:(By python)
1. 两次循环求解
2. 使用python字典存储方式
格式---- 数值:对应下标
此复杂度为O(n)。
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.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
题意:
在数组中返回2个数之和为目标数的下标。
题解:(By python)
1. 两次循环求解
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i+1,len(nums)): if nums[i]+nums[j]==target: return [i,j]此复杂度为O(n^2)。
2. 使用python字典存储方式
格式---- 数值:对应下标
class Solution(object): def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ all = {} #定义字典 for item in range(len(nums)): if target-nums[item] in all: return [all[target-nums[item]],item] all[nums[item]]=item #存入字典
此复杂度为O(n)。
相关文章推荐
- [LeetCode]1. Two Sum
- LeetCode.Problem 1 Two Sum
- LeetCode:two sum
- leetcode Two Sum
- LeetCode- Two Sum - Frequent
- LeetCode(1) || Two Sum
- LeetCode(62)-Two Sum
- leetcode 1 two sum 刷题学习笔记
- Leetcode 1. Two Sum
- LeetCode刷题笔记 01 Two Sum
- Two Sum -- LeetCode
- [LeetCode 题解]: Two Sum
- leetcode 1 Two Sum
- 【leetcode】 Two Sum
- Leetcode —— Two Sum
- LeetCode-问题1-Two Sum
- Leetcode 之第一题 two sum
- 【python】【leetcode】【算法题目1—Two Sum】
- leetcode Two Sum
- [leetcode, python] Two Sum 两数之和等于某数