zoukankan      html  css  js  c++  java
  • LeetCode每周记录-5

    将两串链表合并成一串(保持有序)。题目很简单,思路是用两个指针分别遍历两串链表,同时比较节点值,取小的那一边并将指针向右移动。代码:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeTwoLists(self, l1, l2):
            """
            :type l1: ListNode
            :type l2: ListNode
            :rtype: ListNode
            """
            if not l1 and not l2:
                return None
            if not l1:
                start = l2
            elif not l2:
                start = l1
            else:
                start = l1 if l1.val <= l2.val else l2
            if start == l1:
                p, q = start.next, l2
            else:
                p, q = l1, start.next
            currNode = start
            while(p or q):
                if p and q:
                    if p.val <= q.val:
                        currNode.next = p
                        currNode = p
                        p = p.next
                    else:
                        currNode.next = q
                        currNode = q
                        q = q.next
                elif p:
                    currNode.next = p
                    currNode = p
                    p = p.next
                elif q:
                    currNode.next = q
                    currNode = q
                    q = q.next
                else:
                    pass
            return start
                
            

    给出一个整数n,用n个括号()来组成不同的字符串,给出所有的可能。思路是利用括号的合法要求,通过递归,在2 * n长度的字符串中按从左到右的顺序添加左括号或右括号,每添加一个左括号将其加入到一数组中存储,每添加一个右括号检查数组中是否有剩余的左括号(有则删除一个左括号,无则停止递归),在中途有提前停止递归的一些方法(比如左括号的数量已经超过了n),递归停止时左括号剩余0个,则得到一个可能性。代码:

    class Solution(object):
        def generateParenthesis(self, n):
            """
            :type n: int
            :rtype: List[str]
            """
            allParentheses = []
            tempSave = []
            _tempSave = ''
            self._generateParenthesis(tempSave, _tempSave, '(', allParentheses, n - 1, n)
            return allParentheses
        
        def _generateParenthesis(self, tempSave, _tempSave, sign, allParentheses, leftCount, rightCount):
            _tempSave += sign
            if leftCount == 0 and rightCount == 0:
                if tempSave[-1] == '(' and sign == ')':
                    allParentheses.append(_tempSave)
                return
            if sign == ')':
                if tempSave and tempSave[-1] == '(':
                    tempSave.pop()
                    if leftCount > 0:
                        self._generateParenthesis([x for x in tempSave], _tempSave, '(', allParentheses, leftCount - 1, rightCount)
                    if rightCount > 0:
                        self._generateParenthesis([x for x in tempSave], _tempSave, ')', allParentheses, leftCount, rightCount - 1)
                else:
                    return
            else:
                tempSave.append(sign)
                if leftCount > 0:
                    self._generateParenthesis([x for x in tempSave], _tempSave, '(', allParentheses, leftCount - 1, rightCount)
                if rightCount > 0:
                    self._generateParenthesis([x for x in tempSave], _tempSave, ')', allParentheses, leftCount, rightCount - 1)

    合并k个有序链表,返回一个有序链表。思路是用数组来帮忙存储所有节点的值,最后利用记录下来的所有值重新创建一个新的链表。代码:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def mergeKLists(self, lists):
            """
            :type lists: List[ListNode]
            :rtype: ListNode
            """
            mergeList = []
            for _list in lists:
                tempList = []
                p = _list
                while(p):
                    tempList.append(p.val)
                    p = p.next
                mergeList += tempList
            mergeList.sort()
            start, p, q = None, None, None
            print mergeList
            if mergeList:
                for i in mergeList:
                    node = ListNode(i)
                    if not start:
                        start = p = q = node
                    else:
                        if p == q:
                            q = node
                            p.next = q
                        else:
                            p = q
                            q = node
                            p.next = q
            return start
                        
                    
                    
                

    给出一串链表,将这串链表节点两两置换(前后位置交换,不能通过改变值实现)。按着题目的要求做节点的位置交换即可,注意做完置换后跳到下一组节点的位置,以及置换后与相邻节点联系的建立。代码:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def swapPairs(self, head):
            """
            :type head: ListNode
            :rtype: ListNode
            """
            if not head:
                return
            if not head.next:
                return head
            p = q = head
            while(p and p.next):
                _p = p
                pnext = p.next
                if q == head:
                    head = pnext
                    _p.next = pnext.next
                    head.next = _p
                    p = _p.next
                else:
                    q.next = pnext
                    _p.next = pnext.next
                    pnext.next = _p
                    p = _p.next
                q = _p
            return head
            

    上一题的升级版,给出一串链表,每k个节点进行一次逆序操作(不满k个节点则不进行操作)。思路是用数组帮忙实现,一边遍历链表,一边将节点存储到数组中,每存储k个节点,对数组进行逆序操作,然后将逆序后的头尾节点与链表重新连结起来。代码:

    # Definition for singly-linked list.
    # class ListNode(object):
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution(object):
        def reverseKGroup(self, head, k):
            """
            :type head: ListNode
            :type k: int
            :rtype: ListNode
            """
            if k <= 1:
                return head
            tempList = []
            i = 0
            p = q = head
            while(p or i == k):
                if i == k:
                    if q == head:
                        tempList.reverse()
                        head = tempList[0]
                        for j, node in enumerate(tempList[0:-1]):
                            node.next = tempList[j + 1]
                    else:
                        tempList.reverse()
                        q.next = tempList[0]
                        for j, node in enumerate(tempList[0:-1]):
                            node.next = tempList[j + 1]
                    tempList[-1].next = p
                    q = tempList[-1]
                    i = 0
                    tempList = []
                i += 1
                tempList.append(p)
                p = p.next if p else None
            return head

    给出一个有序整数数组,将里面重复的数移除。由于是有序数组,相同的数一定在一起,所以用一个变量记录上一个数的值即可,遍历一遍数组,遇到与上一个数相同的进行删除,同时遍历的序号不增;不同的话则不进行操作,序号增加。

    class Solution(object):
        def removeDuplicates(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return
            i = 1
            currNum = nums[0]
            while(i <= len(nums) - 1):
                if nums[i] == currNum:
                    nums.pop(i)
                else:
                    currNum = nums[i]
                    i += 1
            return len(nums)

    (27题在之前的博客中做过)。给出总字符串和目标字符串,找出目标字符串在总字符串中的位置,返回位置序号或者-1。利用Python字符串的index即可。

    class Solution(object):
        def strStr(self, haystack, needle):
            """
            :type haystack: str
            :type needle: str
            :rtype: int
            """
            try:
                return haystack.index(needle)
            except:
                return -1
            
  • 相关阅读:
    CSS优先级及继承
    group by 与 order by
    软件开发升级指南(转)
    安装DELL服务器,安装Windows 2003 sp2 问题
    SQL SERVER 2005数据库总结
    C#操作INI文件(调用WindowsAPI函数:WritePrivateProfileString,GetPrivateProfileString)
    对RBS理解与使用
    WSS和MOSS的区别
    关于.net winform ComboBox数据绑定显示问题
    OpenNETCF.Desktop.Communication.DLL程序集的使用
  • 原文地址:https://www.cnblogs.com/HorribleMe/p/12728087.html
Copyright © 2011-2022 走看看