Two-part search summary and partial lintcode topic analysis 1

Source: Internet
Author: User
Tags lintcode

Two-part Search course review and summary, including the following aspects, the template of the dichotomy to summarize the idea of the problem, application.

Two-way Template summary classical binary search:

1. It is necessary to exclude extreme situations, that is, the array (denoted by a) does not exist that is a = = None or A is empty, that is, Len (A) = = 0.

2. Two The core of the method is to find the mid value, and determine whether the mid is consistent with the target we are looking for, or the relationship between target, so we must first determine the start and end. Assign start and end values, start = 0, end = Len (A)-1

3. Then a while loop is used to find out whether there is a target or target position, range, or not, with the start + 1 < end to avoid a dead loop.

and have mid = start + (End-start)/and avoid overflow

4. Determine the relationship between A[mid] and target, and what assignment to take to retain half of the solution, that is, start = = Mid or end = = Mid

5. The value of A[start] and A[end] may be the same as the target, but the condition for start + 1 < end is false, so it is also determined that the two values are consistent with the target outside of the loop.

6. If they are not equal, return null

Below, we give the solution of classical binary search, which is a simple and typical problem of binary search on index.

Class solution:    # @param {int[]} A integer array sorted in ascending order    # @param {int.} target an integer
   
    # @return {int} an integer    def findposition (self, A, target):        # They was different        if A is None or len (a) = = 0:            return-1        # Set start and end        end = Len (A)-1        start = 0        # While loop, with start + 1 < end to A void dead Loop while        (start + 1 < end):            mid = start + (end-start)/2            if a[mid] = = target:                retu RN mid            elif A[mid] > target:                # start. Mid.. End, target in start. Mid                end = Mid            else:                start = Mid        if a[start] = = target:            return start        if a[end] = = Target:
    return End        Return-1
   

The classic algorithm can be expanded to the first position or the last position, is a typical example of binary search on index, in both cases, even if the corresponding elements are found in order to determine whether the initial or final position, In fourth fifth step to be different ~ take last position as an example

while (start + 1 < end):            mid = start + (end-start)/2            if a[mid] = = Target:                start = Mid            elif A[mid] > Target:                # start. Mid.. End, target in start. Mid                end = Mid            else:                start = Mid        if a[end] = = target:            return end        if a[start] = = target:            retu RN Start        

Similar to the search a 2D matrix problem, just to expand the two-dimensional array into a one-dimensional array, continue to use the two-way template above can be solved

Class solution: "" "    @param Matrix, a list of lists of integers    @param target, an integer    @return a Boolean , indicate whether matrix contains target    "" "    def Searchmatrix (self, Matrix, target):        If the matrix is None or len (matrix) = = 0:            return False        m = len (matrix)        n = Len (matrix[0])        start = 0        end = m * N-1 while        ( Start + 1 < end):            mid = start + (end-start)/2 Line            = mid/n            column = mid% n            if matrix[line][c Olumn] = = target:                return True            elif Matrix[line][column] < target:                start = Mid            else:                end = Mid        if matrix[(start/n) [(Start% n)] = = target:            return True        if matrix[(end/n) [(end% n)] = = Target:
   return True        return False

Search insert position as long as you hold the dichotomy an important feature is to judge the condition, it can be converted to find first position >= target problem

Class solution: "" "    @param a:a list of integers    @param target:an integer to is inserted    @return: an I Nteger "" "    def searchinsert (self, A, target):        # Find the position whose value was equal or more than target
   
    # only consider no duplicates conditions        if A is None or len (a) = = 0:            return 0        start = 0        end = Len (a)- 1 while        (start + 1 < end):            mid = start + (end-start)/2            if A[MID] >= target:                end = Mid            E LSE:                start = Mid        if A[start] >= target:            return start        if A[end] >= target:            return end
    
# a condition that the target was more than all of the elements in array if A[end] < target: return end + 1 return-1

Two-part search summary and partial lintcode topic analysis 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.