Leetcode 算法题13

326. Power of Three

判断一个数是否为3的N次方,要求不使用循环/递归

我的代码:理解错意思,用了递归

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 0:return False
        if n == 1:
            return True
        elif n % 3 == 0:
            return self.isPowerOfThree(n/3)
        else:
            return False

之后用的调用log函数:也改了很久,因为有类似log(243,3)的结果为4.99999

class Solution(object):
    def isPowerOfThree(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n <= 0:return False
        else:
            return 3**round(math.log(n,3)) == n

大神的代码:利用了int类型最大位限制,2.7版本中3的n次方最多到1162261467,再多就要换成long int,在python3里应该也能找到最大位数限制

class Solution(object):
    def isPowerOfThree(self, n):
        return n > 0 and 1162261467 % n == 0
我TM很疑惑啊,说了不让用循环/递归,discuss里提交的python全是用while的,看了solution,除了常规循环,还有换算成3进制,看是否为‘1000*’


231. Power of Two

与上题一致,但没有要求,就直接用了递归

class Solution(object):
    def isPowerOfTwo(self, n):
        """
        :type n: int
        :rtype: bool
        """
        if n == 0:return False
        if n == 1:
            return True
        elif n % 2 == 0:
            return self.isPowerOfTwo(n/2)
        else:
            return False

645. Set Mismatch

给出一个1~n的列表,抹掉一个数字,加入另一个书的复制,找到这个复制的数和缺失的数

Example 1:

Input: nums = [1,2,2,4]
Output: [2,3]
我的代码:本来想用Counter,但是遍历一遍又遍历感觉不好,就写了一个只需要遍历一遍的代码

class Solution(object):
    def findErrorNums(self, nums):
        """
        :type nums: List[int]
        :rtype: List[int]
        """
        dic={}
        len_ = 0
        sum_ = 0
        for i in nums:
            if dic.get(i,0) == 1:
                dup = i
            else:
                dic[i] = 1
            len_ += 1
            sum_ += i
        miss =(len_ + 1)*len_/2 - (sum_ - dup)
        return (dup,miss)

大神的两种,第一种也是遍历了两遍:

def findErrorNums(self, A):
    N = len(A)
    count = [0] * (N+1)
    for x in A:
      count[x] += 1
    for x in xrange(1, len(A)+1):
        if count[x] == 2:
            twice = x
        if count[x] == 0:
            never = x
    return twice, never
Bonus solution: Say  (x, y)  is the desired answer. We know  sum(A) - x + y = sum([1, 2, ..., N]) , and  sum(x*x for x in A) - x*x + y*y = sum([1*1, 2*2, ..., N*N]) . So we know  x-y  and  x*x-y*y . Dividing the latter by  x-y , we know  x+y . Hence, we know  x  and  y .
def findErrorNums(self, A):
    N = len(A)
    alpha = sum(A) - N*(N+1)/2
    beta = (sum(x*x for x in A) - N*(N+1)*(2*N+1)/6) / alpha
    return (alpha + beta) / 2, (beta - alpha) / 2
第二种方法思路很好,但是代码计算量变大了


83. Remove Duplicates from Sorted List

输入一个已排序过的节点连接列表,去除其中所有重复的数

我的代码:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def deleteDuplicates(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if head == None:return head
        pre = head
        cur = head.next
        while cur:
            if pre.val == cur.val:
                pre.next = cur.next
                cur = pre.next
            else:
                pre , cur = pre.next,cur.next
        return head
大神的代码:一个指针

def deleteDuplicates(self, head):
    cur = head
    while cur:
        while cur.next and cur.next.val == cur.val:
            cur.next = cur.next.next     # skip duplicated node
        cur = cur.next     # not duplicate of current node, move to next node
    return head

191. Number of 1 Bits

输入一个数,求这个数转为二进制后含有‘1’的个数

我的代码:

class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        return bin(n).count('1')
这个问题的答案五花八门,我给的有点tricky的意思,给出几个其他答案
用移位判断
def hammingWeight(self, n):
    return len([i for i in range(32) if (1<<i)&n])  
用递归,但是在定义函数时加了一个count
def hammingWeight(self, n, count=0):
    return self.hammingWeight(n & n-1, count+1) if n!=0 else count 
用循环
class Solution(object):
    def hammingWeight(self, n):
        """
        :type n: int
        :rtype: int
        """
        ans=0
        while n>0:
            if n%2==1:
                ans+=1
            n=n/2       #这里应该是地板除,python3中用 n = n//2
        return ans



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值