167. Two Sum II

https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

Restatement

Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution and you may not use the same element twice.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

Analysis

As the array is in ascending order, which is more specific than the array in sorted order, it is easy to think of the begining-and-end two pointers technique. (A classic problem is Reverse the characters in a sting. ) 

One pointer starts from the beginning while the other pointer starts from the end. And they move toward each other. Then define the sum of the two values which pointers point at, and if the sum equals to the target, then output the two pointers plus one. Nevertheless, if the sum is less than the target, advance the beginning pointer to next character. If the sum is larger than the target, then advance the end pointer towards the beginning of the array. 

Solution

class Solution(object):
    def twoSum(self, A, target):
        left=0
        right=len(A)-1
        while left < right:
            sum = A[left] + A[right]
            if sum < target:
                left += 1
            elif sum > target:
                right -= 1
            else:
                return left+1, right+1

Note

1. The pointer of an array in Python with the length of len(A) starts from 0 to len(A)-1, rather than 1 to len(A). Pay particular attention when the pointer is in the while loop, where the maxium value of the pointer is len(A)-1, otherwise the list overflows.  

2. Since we use the begining-and-end two pointers technique. The operating condition of two pointers is 

while left < right:

then put other specific conditions below.

3 It is not okay to update left or right more than 1. Time exceeds error. The binary search solution is below. 

My ans

class Solution(object):
    def twoSum(self, A, target):
        if len(A) == 0:
            return 0
        j = 0
        while (j < len(nums)):
            i=j
            for i in range(0,len(A)) :
                    if A[i] == target-A[j] and (i != j):
                        return  min(i,j)+1, max(i,j)+1
                    else:
                        j=j+1

Diagnosis

???

Traps

1. My ans applies the slow-and-fast technique, which is commenly used for sorted arrays, and the worst situation is to scan the whole array twice. However, in this case, given the ascending order, it is way faster to use the beginning-and-end technique. 

2. To be continued....

Other notable solutions

# dictionary           
def twoSum2(self, numbers, target):
    dic = {}
    for i, num in enumerate(numbers):
        if target-num in dic:
            return [dic[target-num]+1, i+1]
        dic[num] = i
 
# binary search        
def twoSum(self, numbers, target):
    for i in xrange(len(numbers)):
        l, r = i+1, len(numbers)-1
        tmp = target - numbers[i]
        while l <= r:
            mid = l + (r-l)//2
            if numbers[mid] == tmp:
                return [i+1, mid+1]
            elif numbers[mid] < tmp:
                l = mid+1
            else:
                r = mid-1

Binary Search Note:

1 Before we go to the BS, part, iterate the left poiner by step 1 and set right as the last index.

2 The BS check condition is :

tmp = target - numbers[i]  # tmp is the current value of right pointer. 

if numbers[mid] == tmpBS check condition: If the current right pointer value eqauls to the mid value.  If they are not the same, we will transform the mid value to another range.

# BS check condition is NOT target == left_value + right_value

原文地址:https://www.cnblogs.com/prmlab/p/6367993.html