11-15 questions of sword finger offer -- python implementation

'''
11. Title Description
Given a floating-point base of type double and an integer of type int, exponent. Find the exponent power of base.
'''

class Solution:
    def Power(self, base, exponent):
        if base==0:
            return 0
        if exponent==1:
            return 1
        else:
            if exponent<0:
                result = base**(-exponent)
                return 1/result
            else:
                return base**exponent

'''
13. Title Description
Input an integer array and implement a function to adjust the order of the numbers in the array,
Make all odd numbers in the first half of the array, all even numbers in the second half of the array, and ensure that the relative positions between odd numbers and odd numbers, even numbers and even numbers remain unchanged.
'''

class Solution:
    def reOrderArray(self, array):
        odd = []
        double = []
        n = len(array)
        for j in range(n):
            i = j
            while i>0:
                if array[i]<array[i-1]:
                    array[i],array[i-1]=array[i-1],array[i]
                else:
                    break
        for k in range(n):
            if array[k] % 2 == 0:
                double.append(array[k])
            else:
                odd.append(array[k])
        return odd+double

'''
14. Title Description
Input a list and output the k last node in the list.
'''

class Solution:
    def FindKthToTail(self, head, k):
        result = []
        while head:
            result.append(head)
            head = head.next
        if k>len(result) or k==0:
            return []
        else:
            return result[-k]

'''
15. Title Description
Input a linked list, reverse the linked list, and output the header of the new linked list.
'''

class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    # Return to ListNode
    def ReverseList(self, pHead):
        lis = []
        pRes = ListNode(-1)
        pRes.next = pHead
        if not pHead:
            lis = []
        while pHead:
            lis.append(pHead.val)
            pHead = pHead.next
        newList = lis[::-1]
        temp = pRes.next
        for i in range(len(newList)):
            pRes.next.val = newList[i]
            pRes = pRes.next
        return temp``

Posted by kykin on Fri, 20 Dec 2019 10:39:40 -0800