LeetCode Two Sum II - Input array is sorted (Two pointer) (golang)

Problem
在这里插入图片描述
Basics

Two pointers

The essence of two Pointers algorithm is to set two Pointers i,j(i.e., i <j) to point to the element to be solved respectively (i.e., i <j), and then move the two Pointers in the same direction or in the opposite direction. The move ends when i >=j

The time and space complexity of the non-recursive writing of merge sort, quick sort, sequence merge, and the median of two pointer algorithm in PAT1029 to find two sequences are reduced to O(N) compared with the complexity of the algorithm not used, and two Pointer is better to be used in the problems requiring running time and running memory

analytic process

Initially, the two Pointers point to the location of the first element and the location of the last element
Each time, the sum of the two elements pointed to by the two Pointers is calculated and compared with the target value
If the sum of the two elements is equal to the target value, then a unique solution is found.
If the sum of the two elements is less than the target value, then move the left pointer to the right one place
If the sum of the two elements is greater than the target value, the right pointer is moved one bit to the left
After you move the pointer, repeat until you find the answer

Consider the following special cases
1.If the left pointer reaches the position of subscript i first, then the right pointer is still to the right of the subscript j ,sum>target, so the right pointer must move to the left, the left pointer cannot move to the right of i
2.If the right pointer reaches the position of subscript j first, then the left pointer is still to the left of the subscript i. sum <target therefore must move the left pointer to the right, and the right pointer cannot move to the left of j

code

func twoSum(numbers []int, target int) []int {
    i,j := 0, len(numbers) - 1            //set the left and right Pointers
    for i < j {
        sum := numbers[i] + numbers[j]    //calculates the sum of the elements to which the two Pointers point
        if sum == target {                
         return []int{i + 1, j + 1}  //if equal to the target value, returns the index indicated by the pointer
        } else if sum < target {
            i++                      //the left pointer moves left
        } else {
            j--                     //the right pointer moves right
 
        }
    }
    return []int{-1, -1}
}

猜你喜欢

转载自blog.csdn.net/qq_46595591/article/details/107474862