python(剑指offer11-16题)

11.输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。重点在补码上

class Solution:
    def NumberOf1(self, n):
        # write code here
        if n>=0:
            count = bin(n).count('1')
        else:
            n=abs(n)
            count = 32 - bin(n-1).count('1')
        return count

13.输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。python 生成器

class Solution:
    def reOrderArray(self, array):
        # write code here
        odd = [x for x in array if x%2 == 1]
        even = [x for x in array if x%2 == 0]
        return odd + even

14.输入一个链表,输出该链表中倒数第k个结点。还是运用了python数组的技巧,需要判断是否越界

class Solution:
    def FindKthToTail(self, head, k):
        # write code here
        li = []
        while head:
            li.append(head)
            head = head.next
        if k > len(li) or k == 0:
            return None
        return li[-k]

15.输入一个链表,反转链表后,输出新链表的表头。类似于指针,使链表指向自己的前一个元素。

class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if not pHead:
            return None
        pre = None
        cur = pHead
        head = pHead
        while cur:
            head = cur
            tem = cur.next
            cur.next = pre
            pre = cur
            cur = tem
        return head

16输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

class Solution:
    # 返回合并后列表
    def Merge(self, pHead1, pHead2):
        # write code here
        # 若两个链表为空返回False
        if not pHead1:
            return pHead2
        if not pHead2:
            return pHead1
        # 若第一个大于等于第二个的头就将链表2后移一位 否则就将1后移一位
        if pHead1.val >= pHead2.val:
            pHead2.next = self.Merge(pHead1, pHead2.next)
            return pHead2
        else:
            pHead1.next =self.Merge(pHead1.next, pHead2)
        return pHead1

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值