[leetcode]中级算法——其他

本文探讨了几个经典算法问题,包括不使用加减运算符实现两整数相加、逆波兰表达式求值、求众数以及任务调度器算法。通过不同解法对比,展示了算法设计的多样性和效率考量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

两整数之和

Calculate the sum of two integers  a  and  b , but you are  not allowed  to use the operator  +  and  - .

Example:

Given  a  = 1 and  b  = 2, return 3.

Code(By myself):

class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        return sum([a,b])
Code(others):
class Solution(object):
    def getSum(self, a, b):
        """
        :type a: int
        :type b: int
        :rtype: int
        """
        while b != 0:
            carry = a & b
            a = (a ^ b) % 0x100000000
            b = (carry << 1) % 0x100000000
        if a <= 0x7FFFFFFF:
            return a
        else:
            return a | (~0x100000000 + 1)
总结:

可使用二进制加法运算求出结果

逆波兰表达式求值

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +-*/. Each operand may be an integer or another expression.

Note:

  • Division between two integers should truncate toward zero.
  • The given RPN expression is always valid. That means the expression would always evaluate to a result and there won't be any divide by zero operation.

Example:

Input: ["2", "1", "+", "3", "*"]
Output: 9
Explanation: ((2 + 1) * 3) = 9

Code(By myself):

class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        stack = []
        for i in tokens:
            if i not in ['+','-','*','/']:
                stack.append(int(i))
            else:
                a = stack.pop()
                b = stack.pop()
                if i == '+':
                    res = b + a
                elif i == '-':
                    res = b - a
                elif i == '*':
                    res = b * a
                elif i == '/':
                    if (a>0 and b<0) or (a<0 and b>0):
                        res = - abs(b)/abs(a)
                        if abs(b)%abs(a) != 0:
                            res += 1
                    else:
                        res = b / a
                stack.append(res)
        return stack[0]
Code(others):
class Solution(object):
    def evalRPN(self, tokens):
        """
        :type tokens: List[str]
        :rtype: int
        """
        def op(char,a,b):
            if char == '+':
                return a + b
            elif char == '-':
                return a - b
            elif char == '*':
                return a * b
            else:
                if a:
                    sign = (a * b) / abs(a * b)
                else:
                    sign = 1
                return sign * (abs(a) / abs(b))
        opSet = set('+-*/')
        numStack = []
        for x in tokens:
            if x in opSet:
                # print x
                op2 = numStack.pop()
                op1 = numStack.pop()
                numStack.append(op(x,op1,op2))
            else:
                numStack.append(int(x))
            # print numStack
        return numStack[-1]

求众数

Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.

You may assume that the array is non-empty and the majority element always exist in the array.

Example:

Input: [3,2,3]
Output: 3

Code(By myself):

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        length = len(nums)
        for i in set(nums):
            if nums.count(i) > length // 2:
                return i

Code(others):

class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        return sorted(nums)[len(nums)//2]       

任务调度器

Given a char array representing tasks CPU need to do. It contains capital letters A to Z where different letters represent different tasks.Tasks could be done without original order. Each task could be done in one interval. For each interval, CPU could finish one task or just be idle.

However, there is a non-negative cooling interval n that means between two same tasks, there must be at least n intervals that CPU are doing different tasks or just be idle.

You need to return the least number of intervals the CPU will take to finish all the given tasks.

Example:

Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Code(others):
class Solution(object):
    def leastInterval(self, tasks, n):
        """
        :type tasks: List[str]
        :type n: int
        :rtype: int
        """
        size = len(tasks)
        if n == 0:
            return size
        
        # 统计每个任务需要执行的次数
        ORD_A = ord('A')
        freqs = [0] * 26
        for task in tasks:
            freqs[ord(task) - ORD_A] += 1
        
        # 找出次数最多的任务需要执行的次数
        freqs.sort(reverse=True)
        freqmax = freqs[0]
        
        freqmaxcnt = 0
        for freq in freqs:
            if freq == freqmax:
                freqmaxcnt += 1
        
        return max(size, (freqmax - 1) * (n + 1) + freqmaxcnt) 
总结:

算法可参考插空法1插空法2队列





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值