很简单的一道题目:
1.Two Sum
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].
第一次写的:
class Solution:
def twoSum(self, nums, target: int) :
for i in range(0,len(nums)):
for j in range(i+1,len(nums)):
if i!=j and nums[i] + nums[j] == target:
return [i,j]
当list很大的时候很很慢,而且没有那么复杂😳
第二次写的:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(0,len(nums)):
if target - nums[i] in nums:
if i != nums.index(target - nums[i]) :
return [i,nums.index(target - nums[i]) ]
性能大大提高,如果换做是你 ,你会怎么做?
这是题库中的第一题,也是最简单的一题,受挫