Question:
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:
|
|
My First answer: (wrong)
|
|
|
|
so we need to clear the index and value, exchange their position to make them uniqueness
Modified Answer:
|
|
Traverse the list, and put every item into the list d
, and the order of return list
is also important, first is index in list d
, because the item in list d
is earilier put from the origin list i.e. list nums
. Second is current index in list nums
.
Complexity Analysis:
- Time complexity:O (n),for each element , we try to find its complement by looping through the rest of array which takes O (n) time
- Space complexity:O (1)
Supplement:
List
list1 = ['physics', 'chemistry', 1997, 2000]
list.append(x)
: Add an item x to the end of the list
list.extend(list)
: Extend the list by appending all the items in the given list
list.insert(i,x)
list.remove(x)
: the first item from the first
list.pop([i])
: Remove the item at the given position in the list, and return it
list.index(x)
list.count(x)
list.sort()
list.reverse()
del(list[2])
len(list)
cmp(list1,list2)
max(list),min(list)
['Hi']*4
3 in [1,2,3]
for x in [1,2,3]
list[2]
: the third item in the list
list[-2]
: the second last item in the list
list[1:]
: read the list beginning from the second item
enumerate(sequence, [start=0])
()
|
|