编程能力提升_7

目录

1.编写一个算法来判断一个数是不是“快乐数”。

2.删除链表中等于给定值 val 的所有节点。

3.统计所有小于非负整数 n 的质数的数量。

4.给定两个字符串 s 和 t,判断它们是否是同构的。

5.反转一个单链表。

6.给定一个整数数组,判断是否存在重复元素。

7.给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 i 和 j 的差的绝对值最大为 k。

8.使用队列实现栈的下列操作:

9.翻转一棵二叉树。


1.编写一个算法来判断一个数是不是“快乐数”。

一个“快乐数”定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是无限循环但始终变不到 1。如果可以变为 1,那么这个数就是快乐数。

示例: 

输入: 19
输出: true
解释: 
12 + 92 = 82
82 + 22 = 68
62 + 82 = 100
12 + 02 + 02 = 1

方法一:

class Solution:
    def isHappy(self, n):
        """
        :type n: int
        :rtype: bool
        """        
        #利用 set()集合,保存平方求和后的数值
        mem ={}       
        while n != 1:            
            #通过str(n)调取输入整数各个位数的值
            n = sum([int(i)**2 for i in str(n)])  
            #若平方求和后的数值是首次出现,则添加进集合中
            if n not in mem:                       
                mem[n]=n
            #若求和后数值,在集合中存在,则直接返回false,即出现死循环
            else:               
                return False
        #最终当n==1时,跳出while循环,返回true
        return True   

方法二:

class Solution:
    def isHappy(self, n):
        while n!=1:
            s=0
            while n>0:
                s=s+(n%10)**2
                n=n//10
            if s ==4:
                return False
            n=s
        return  True

2.删除链表中等于给定值 val 的所有节点。

示例:

输入: 1->2->6->3->4->5->6, val = 6
输出: 1->2->3->4->5

方法一:构建虚拟节点 begin=ListNode(0);      begin.next=head;    return begin.next

class Solution(object):
    def removeElements(self, head, val):
        #因为有可能头结点会被删除所以构造虚拟头结点
        pa=source=ListNode(0)
        pa.next=head
        while(pa):
            while(pa.next and pa.next.val==val):
                #删除连续出现与val等值的情况
                pa.next=pa.next.next
            pa=pa.next
        return source.next

方法二:

class Solution(object):
    def removeElements(self, head, val):
        #因为有可能头结点会被删除,所以将头结点放到最后最后处理
        newhead=head
        while head:
            if head.next and head.next.val==val:
                #每次都判断下一节点
                head.next=head.next.next
            else:                
                head=head.next
        if newhead and newhead.val==val:
            newhead=newhead.next
        return newhead

3.统计所有小于非负整数 的质数的数量。

示例:

输入: 10
输出: 4
解释: 小于 10 的质数一共有 4 个, 它们是 2, 3, 5, 7 。
class Solution:
    def countPrimes(self, n: int) -> int:
        if n < 3:
            return 0     
        else:
            # 首先生成了一个全部为1的列表
            output = [1] * n
            # 因为0和1不是质数,所以列表的前两个位置赋值为0
            output[0],output[1] = 0,0
            # 此时从index = 2开始遍历,output[2]==1,即表明第一个质数为2,然后将2的倍数对应的索引
            # 全部赋值为0. 此时output[3] == 1,即表明下一个质数为3,同样划去3的倍数.以此类推.
            for i in range(2,int(n**0.5)+1):
                if output[i] == 1:
                    m = i**2 #起始点就是i平方,因为2*i,3*i在i==3时已经消除,不用重复计算,2*i也可以
                    while m < n:  # 循环遍历到列表最后一个元素
                        output[m] = 0
                        m += i  # 循环间隔为i
        # 最后output中的数字1表明该位置上的索引数为质数,然后求和即可.
        return sum(output)

4.给定两个字符串 和 t,判断它们是否是同构的。

如果 中的字符可以被替换得到 ,那么这两个字符串是同构的。所有出现的字符都必须用另一个字符替换,同时保留字符的顺序。两个字符不能映射到同一个字符上,但字符可以映射自己本身。

示例 1:

输入: s="egg"

t = "add"

输出: true

方法一:

class Solution(object):
    def isIsomorphic(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        DictA = {}
        DictB = {}
        for i in range(len(s)):
            if s[i] in DictA.keys():
                #如果s[i]与之对应的t[i]在后续不等则返回False,例如aabc;ccdf
                if DictA[s[i]] != t[i]:
                    return False
            else:
                DictA[s[i]] = t[i]
        for i in range(len(t)):
            if t[i] in DictB.keys():
                #如果t[i]与之对应的s[i]在后续不等则返回False,例如aabc;ccdd
                if DictB[t[i]]!= s[i]:
                    return False
            else:
                DictB[t[i]]=s[i]
        return True

方法二:

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        return len(set(s)) == len(set(t)) == len(set(zip(s, t)))

5.反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
class Solution(object):
    def reverseList(self, p):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        stack = [None]
        while p:
            stack.append(p)
            p = p.next
        head = stack.pop()
        p = head
        while p:
            p.next = stack.pop()
            p = p.next
        return head

方法二:迭代法

class Solution:
    def reverseList(self, head):
        rev = None
        p = head
        while p:         
            temp=p
            p=p.next
            #连接当前节点与下一节点
            temp.next=rev
            rev=temp
        return rev

6.给定一个整数数组,判断是否存在重复元素。

如果任何值在数组中出现至少两次,函数返回 true。如果数组中每个元素都不相同,则返回 false。

示例 1:

输入: [1,2,3,1]
输出: true

方法一:

class Solution:
    def containsDuplicate(self, nums: List[int]) -> bool:
        dic={}
        for i in nums:
            if i in dic:
                return True
            else:
                dic[i]=i
        return False

方法二:

class Solution(object):
    def containsDuplicate(self, nums):
        """
        :type nums: List[int]
        :rtype: bool
        """
        return len(nums)!=len(set(nums))

7.给定一个整数数组和一个整数 k,判断数组中是否存在两个不同的索引 i 和 j,使得 nums [i] = nums [j],并且 ij 的差的绝对值最大为 k

示例 1:

输入: nums = [1,2,3,1], k = 3
输出: true
class Solution(object):
    def containsNearbyDuplicate(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: bool
        """
        dic={}
        for i in range(len(nums)):
            if nums[i] in dic and abs(i-dic[nums[i]])<=k:
                return True
            else:
                #因为要求索引小于k,所以每次对不符合k约束的字典值也要更新
                dic[nums[i]]=i

8.使用队列实现栈的下列操作:

  • push(x) -- 元素 x 入栈
  • pop() -- 移除栈顶元素
  • top() -- 获取栈顶元素
  • empty() -- 返回栈是否为空

注意:

  • 你只能使用队列的基本操作-- 也就是 push to back, peek/pop from front, size, 和 is empty 这些操作是合法的。
  • 你所使用的语言也许不支持队列。 你可以使用 list 或者 deque(双端队列)来模拟一个队列 , 只要是标准的队列操作即可。
  • 你可以假设所有操作都是有效的(例如, 对一个空的栈不会调用 pop 或者 top 操作)。
class MyStack:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.stack = collections.deque([])

    def push(self, x: int) -> None:
        """
        Push element x onto stack.
        """
        self.stack.append(x)

    def pop(self) -> int:
        """
        Removes the element on top of the stack and returns that element.
        """
        return self.stack.pop()
    
    def top(self) -> int:
        """
        Get the top element.
        """
        return self.stack[-1]

    def empty(self) -> bool:
        """
        Returns whether the stack is empty.
        """
        return not self.stack

使用栈实现队列的下列操作:

  • push(x) -- 将一个元素放入队列的尾部。
  • pop() -- 从队列首部移除元素。
  • peek() -- 返回队列首部的元素。
  • empty() -- 返回队列是否为空。
class MyQueue:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.a = []
        

    def push(self, x):
        """
        Push element x to the back of queue.
        :type x: int
        :rtype: void
        """
        #push(x) -- 将一个元素放入队列的尾部。将append的数放到0索引,原有数据依次后移
        self.a.append(x)
        self.a[0], self.a[1:] = self.a[-1], self.a[:-1]

    def pop(self):
        """
        Removes the element from in front of queue and returns that element.
        :rtype: int
        """
        return self.a.pop()
        
        

    def peek(self):
        """
        Get the front element.
        :rtype: int
        """
        return self.a[-1]
        

    def empty(self):
        """
        Returns whether the queue is empty.
        :rtype: bool
        """
        return len(self.a) == 0

9.翻转一棵二叉树。

示例:

输入:

     4
   /   \
  2     7
 / \   / \
1   3 6   9

输出:

     4
   /   \
  7     2
 / \   / \
9   6 3   1

方法一:

class Solution:
    def invertTree(self, root):
        """
        : 非递归写法,利用广度优先遍历
        :type root: TreeNode
        :rtype: TreeNode
        """
        if not root:
            return root
        node = [root]
        while node:
            _node = []
            for i in node:
                i.left,i.right = i.right,i.left
                if i.left:
                    _node.append(i.left)
                if i.right:
                    _node.append(i.right)
            node = _node
        return root

方法二:

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def invertTree(self, root: TreeNode) -> TreeNode:
        if root==None:
            return root
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值