A. Two numbers
To an array of integers, find the two numbers and make them equal to a given number of target .
You need to implement the functions twoSum
required to return these two index numbers, and the first index is less than the second index. Note that the target range is 0 to n--. 1 .
Sample
Example1:
给出 numbers = [2, 7, 11, 15], target = 9, 返回 [0, 1].
Example2:
给出 numbers = [15, 2, 7, 11], target = 9, 返回 [1, 2].
challenge
Either of the following solutions are acceptable:
- O(n) Space, O(nlogn) Time
- O (n) space, (n) Time
Precautions
You may assume that only one set of answers.
The first solution:
class Solution: """ @param numbers: An array of Integer @param target: target = numbers[index1] + numbers[index2] @return: [index1, index2] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here array = [] for i in range(len(numbers)): for j in range(i + 1,len(numbers)): if numbers[i] + numbers[j] == target: return [i,j]
The second solution:
class Solution: """ @param numbers: An array of Integer @param target: target = numbers[index1] + numbers[index2] @return: [index1, index2] (index1 < index2) """ def twoSum(self, numbers, target): # write your code here for i in range(len(numbers)): s = target - numbers[i] if s in numbers and numbers.index(s) != i: if numbers.index(s) > i: return [i,numbers.index(s)] else: return [numbers.index(s),i]
II. Search Insert location
Given a sorted array and a target, if the target value is found in the array index is returned. If not, it will return to the position of the inserted sequence.
You may assume that no duplicate elements in the array.
Sample
[1,3,5,6],5 → 2
[1,3,5,6],2 → 1
[1,3,5,6], 7 → 4
[1,3,5,6],0 → 0
challenge
The time complexity is O (log (n))
class Solution: """ @param A: an integer sorted array @param target: an integer to be inserted @return: An integer """ def searchInsert(self, A, target): # write your code here if target in A: return A.index(target) else: for i in range(len(A)): if A[i] > target: return i return len(A)
Comment:
1. If the target A inside the array, return index.
2. If it is not inside the array A, the insertion position of the array returned. if A [i]> target >> return i, otherwise, all values described are array is larger than A, is inserted into the last position of the array A, i.e. len (A).