& Array list to prove safety offer-

1. circle last remaining number

Children's Day each year, cow-off will prepare some small gifts to visit the orphanage children, this year is also true. As an experienced veteran off HF cattle, naturally we prepared some games. Among them, there is a game like this: First, let the children surrounded by a large circle. He then randomly assigned a number m, so that number of children 0 gettin number. Cried every time m-1 the children sing a song to be out of the line, then any of the gift box in choosing a gift, and not return to the circle, starting with his next child, continue 0 ... m -1 number of packets .... go on .... until the last remaining child, you can not perform, and get the cattle off the rare "Detective Conan" Collector's Edition (limited places oh !! ^ _ ^). You want to try next, which the children will get the gifts it? (NOTE: The number of children is from 0 to n-1)
 
If there are no children, please return -1
solution:
The array can be simulated with a circular linked list.
class Solution:
    def LastRemaining_Solution(self, n, m):
        # write code here
        if not n:
            return -1
        cycle = list(range(n))
        start = 0
        while len(cycle) > 1:
            toremove = (start + m - 1) % len(cycle)
            cycle.pop(toremove)
            start = toremove
        return cycle[0]

  

 

2. array duplicate numbers

All numbers in a length of n in the array are in the range 0 to n-1. Some digital array is duplicated, but do not know how many numbers are duplicated. Do not know each digit is repeated several times. Please find an array of any one of the duplicate numbers. For example, if the length of the input array 7 {2,3,1,0,2,5,3}, then the corresponding output of the first 2 repeating digits.

solution:

A hash table to do on the line, the idea is very simple.

class Solution: 
    # Of special note here - to find any duplicate value and assigned to Duplication [0] 
    # function returns True / False 
    DEF Duplicate (Self, Numbers, Duplication): 
        # Write code here Wallpaper 
        IF Not Numbers: 
            return False 
        HashMap = SET () 
        for Numbers in NUM: 
            IF NUM in HashMap: 
                Duplication [0] = NUM 
                return True 
            hashmap.add (NUM) 
        return False

 

 

3. Build the product array

Given an array A [0,1, ..., n-1], please construct an array B [0,1, ..., n-1], where B is the element B [i] = A [ 0] * A [1] * ... * A [i-1] * A [i + 1] * ... * A [n-1]. You can not use the division.

solution:

This problem is quite ingenious ideas, look at a map to understand. First count even take the next triangle, then pour over the remaining part of that also take into account.

 

class Solution:
    def multiply(self, A):
        if not A:
            return []
        n = len(A)
        B_left = [1]*n
        B_right = [1]*n
        for i in range(1, n):
            B_left[i] = B_left[i-1]*A[i-1]
            B_right[-i-1] = B_right[-i]*A[-i]
        for i in range(n):
            B_left[i] *= B_right[i]
        return B_left

  

 

4. Find a two-dimensional array

(The length of each one-dimensional array of same), each row from left to right in order of ascending sort, to sort each column in a two-dimensional array in order of increasing from top to bottom. A complete function, enter such a two-dimensional array and an integer, it is determined whether the array contains the integer.

solution:

The first idea, to ensure that each row is ordered to find row two.

class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if not array:
            return False
        m, n = len(array), len(array[0])
        
        def binarySearch(target, nums):
            if not nums:
                return False
            left, right = 0, len(nums)-1
            while left <= right:
                mid = left + (right-left)//2
                if nums[mid] == target:
                    return True
                elif nums[mid] > target:
                    right = mid - 1
                else:
                    left = mid + 1
            return False
        
        for i in range(m):
            if binarySearch(target, array[i]):
                return True
        return False

  

Another idea, taking into account the elements of the lower left corner, to the right more, up smaller. As a starting point to the lower left corner of the search, if it is large than the target upward, if less than the target on the right

class Solution:
    # array 二维列表
    def Find(self, target, array):
        # write code here
        if not array:
            return False
        m, n = len(array), len(array[0])
        i, j = m-1, 0
        while i >= 0 and j < n:
            if array[i][j] == target:
                return True
            elif array[i][j] > target:
                i -= 1
            else:
                j += 1
        return False

  

 

The maximum continuous subarray and

HZ occasionally get some professional issues to flicker those non-computer science students. After the test group will finish today, he spoke up: in the old one-dimensional pattern recognition, it is often necessary to calculate the maximum and continuous sub-vector when the vector is a positive whole number, the problem solved. However, if the vector contains a negative number, it should contain a negative number, and expect a positive number next to it would make up for it? For example: {6, -3, -2,7, -15,1,2,2}, and the maximum successive sub-vectors of 8 (beginning from 0, up to the third). To an array and returns its maximum continuous subsequence and you will not be fooled him live? (Sub-vector length is at least 1)

solution:

This problem is actually a basic dp problem, define dp [I] represented by a [i] continuously subvector end of the maximum and, then obviously dp [i] = max (dp [i-1] + array [i], array [i]), that is, if a [i-1] at the end of successive sub-vector is positive on the largest and reserved, otherwise not doing positive contribution, from a [i] to begin direct again.

The last requirement is a maximum contiguous subsequence and may terminate in any position in the array element, is returned max (dp)

class Solution:
    def FindGreatestSumOfSubArray(self, array):
        if array is None or len(array)==0:
            return 
        n = len(array)
        dp = [0]*n
        dp[0] = array[0]
        for i in range(1, n):
            dp[i] = max(dp[i-1] + array[i], array[i])
        return max(dp)

  

 

6. The minimum number k

Input n integers, find the smallest number K. 4,5,1,6,2,7,3,8 e.g. eight digital inputs, the minimum number is four 1,2,3,4 ,.

solution:

Then take the direct quick drain top-k, k N is large but in this case it is not worth a small.

class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if not tinput or k > len(tinput):
            return []
        tinput.sort()
        return tinput[:k]

  

Top with a small heap implementations

import heapq

class Solution:
    def GetLeastNumbers_Solution(self, tinput, k):
        # write code here
        if not tinput or k > len(tinput):
            return []
        n = len(tinput)
        heap =[]
        for i in range(n):
            heapq.heappush(heap, -tinput[i])
            if i >= k:
                heapq.heappop(heap)
        res = list(map(lambda x: -x, list(heap)))
        res.sort()
        return res

  

 

Guess you like

Origin www.cnblogs.com/chaojunwang-ml/p/11442889.html