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]
- 方法一:時間復(fù)雜度O(n*n)
class solution(object):
def twosum(self,nums,target):
b =False
i =0
j =len(nums)-1
while j>0:
while i
if not nums[i]+nums[j]==target :
i +=1
else :
b=True
print( i+1,j+1)
break
j-=1
if not b:
print("null")
sl=solution()
sl.twosum([1,3,7,8],10)
- 方法二:網(wǎng)絡(luò)轉(zhuǎn)載(http://www.cnblogs.com/chruny/p/4788804.html)
class Solution(object):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
def twosum(self,nums,target):
b= False
d ={}
size = 0
print(nums)
while size < len(nums):
if not int(nums[size]) in d:
d[int(nums[size])]=size+1
if target - int(nums[size]) in d:
if d[target - int(nums[size])] < size+1:
b = True
ans = [d[target-int(nums[size])], size+1]
print(ans)
size +=1
if not b:
print("null")
sl=Solution()
sl.twosum(nums=list(input("Please input a list: ")),target=int(input('And input a target:')))
- 筆記:
- len(nums): nums中鍵值對的數(shù)量
- dictionary:字典的增刪改(http://www.runoob.com/python/python-dictionary.html),
鍵必須是唯一的侵浸,但值則不必撑刺。
值可以取任何數(shù)據(jù)類型,但鍵必須是不可變的痢掠,如字符串仓技,數(shù)字或元組
向字典添加新內(nèi)容的方法是增加新的鍵/值對,修改或刪除已有鍵/值對如下實(shí)例:
實(shí)例
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'};
dict['Age'] = 8; # update existing entry
dict['School'] = "DPS School"; # Add new entry
print "dict['Age']: ", dict['Age'];
print "dict['School']: ", dict['School'];
- boolean:定義一個boolean變量,默認(rèn)為false,在其他條件中定義為ture