LeetCode contest-95[876,877,👁878]

876. Middle of the Linked List

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

class Solution:
    def middleNode(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        head2=head
        l=1

        while head.next!=None:
            head=head.next

            l+=1

        w=l//2+1

        l=1
        while head2.next!=None:
            if w==l:
                break
            head2=head2.next

            l+=1
        return head2

877. Stone Game

first submission
import time

class Solution:
    def stoneGame(self, piles):
        """
        :type piles: List[int]
        :rtype: bool
        """
        Alex=0
        Li=0
        flag=True # t is alex,f is li

        i=0
        j=len(piles)-1

        while i<j:

            if piles[i]>=piles[j]:
                num=piles[i]
                i+=1
            else:
                num=piles[j]
                j-=1

            if flag:
                Alex+=num
            else:
                Li+=num

        return Alex>Li
if __name__ == "__main__":

    data = [
        {
            "input":[5,3,4,5],
            "output":True
        },

    ];
    for d in data:

        print(d[‘input‘])

        # 计算运行时间
        start = time.perf_counter()
        result=Solution().stoneGame(d[‘input‘])
        end = time.perf_counter()

        print(result)
        if result==d[‘output‘]:
            print("--- ok ---> spend time: ",end-start)
        else:
            print("--- error ---> spend time: ",end-start)
            break

        print()
    else:
        print("success")

用到了双指针哈哈,开森

878. Nth Magical Number

第N个神奇数字

如果正整数可以被 A 或 B 整除,那么它是神奇的。

返回第 N 个神奇数字。由于答案可能非常大,返回它模 10^9 + 7 的结果。

first submission
class Solution:
    def nthMagicalNumber(self, N, A, B):
        """
        :type N: int
        :type A: int
        :type B: int
        :rtype: int
        """
        num=0
        if A>B:
            A,B=B,A
        ai=1
        bi=1
        for i in range(1,N+1):
            print(i,ai,A*ai,bi,B*bi,end="")
            if A*ai<B*bi:
                num=A*ai
                print("[1]",num)
                ai+=1
            elif A*ai==B*bi:
                num=A*ai
                print("[2]",num)
                ai+=1
                bi+=1
            else:
                num=B*bi
                print("[3]",num)
                bi+=1

        return num
        

Time Limit Exceeded

Last executed input:
1000000000
40000
40000

超时是必然的。最后结束了,就做了两道题。这道超时

看下大神的答案【No.2 [email protected]阳谷县 】

class Solution:
    def gcd(self, a, b):
        if 0 == b:
            return a
        return self.gcd(b, a % b)

    def nthMagicalNumber(self, n, a, b):
        """
        :type N: int
        :type A: int
        :type B: int
        :rtype: int
        """
        c = a * b // self.gcd(a, b)

        lo, hi = 1, 1 << 60

        while lo < hi:
            mid = (lo + hi) // 2
            t = mid // a + mid // b - mid // c

            if t < n:
                lo = mid + 1
            else:
                hi = mid
        return lo % 1000000007
分析一下大神的解法

def gcd() 是求最大公约数

c = a * b // self.gcd(a, b) 求最小公倍数

lo, hi = 1, 1 << 60 构造一个大范围区间,[1,1<<60]

mid = (lo + hi) // 2 当前中点

t = mid // a + mid // b - mid // c 左半区间包含mid // aa,mid // bb,减去含有的最小公倍数个数mid//c,结果t则为左半区间满足数字的个数

if t < n:
    lo = mid + 1
else:
    hi = mid

和目标格式N相比,下个目标区间

END.

第三题总结:其实我也也想到了要用最大公约数或者最小公倍数;想要判断AB含有重复的值。但是不知道可以定义一个大范围,然后二分法判断有多少个数字,以及最小公倍数的使用。数学又挡住了我。

原文地址:https://www.cnblogs.com/warcraft/p/9384942.html

时间: 2024-08-01 07:20:23

LeetCode contest-95[876,877,👁878]的相关文章

(Easy) Diet Plan Performance LeetCode Contest

Description: 5174. Diet Plan Performance My SubmissionsBack to Contest User Accepted:0 User Tried:0 Total Accepted:0 Total Submissions:0 Difficulty:Easy A dieter consumes calories[i] calories on the i-th day.  For every consecutive sequence of k days

LeetCode OJ 95. Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For example,Given n = 3, your program should return all 5 unique BST's shown below. 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 confused what "{1,#,2,3}&

LeetCode(95): 不同的二叉搜索树 II

Medium! 题目描述: 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树. 示例: 输入: 3 输出: [   [1,null,3,2],   [3,2,null,1],   [3,1,null,null,2],   [2,1,3],   [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ 3 2 1 1 3 2 / / \ 2 1 2 3 解题思路: 这种建树问题一般来说都是用递归来

(Easy) Can Make Palindrome - LeetCode Contest (in progress)

Description: Given a string s, we make queries on substrings of s. For each query queries[i] = [left, right, k], we may rearrange the substring s[left], ..., s[right], and then choose up to k of them to replace with any lowercase English letter. If t

LeetCode Contest 177

Number of Days Between Two Dates 计算两个日期的相差天数 public class Solution { public int DaysBetweenDates(string date1, string date2) { DateTime time1 = DateTime.Parse(date1); DateTime time2 = DateTime.Parse(date2); return Math.Abs((time2-time1).Days); } } Va

LeetCode Contest 179

这次终于四题全过了. 这次比赛也确实比较简单 第一题 class Solution { public: string generateTheString(int n) { string str=""; char x='a'; if(n%2==0) { for(int i=0;i<n-1;i++) { str+=x; } str+=(x+1); } else { for(int i=0;i<n;i++) { str+=x; } } return str; } }; 第二题 点

微软原版SQLHelper类

C# Code 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84

axis2生成webservice客户端代码--commond

1. 下载axis2版本http://axis.apache.org/axis2/java/core/download.html 2.下载完成后解压,打开命令行,进入bin目录下,执行命令: ${installdir}>WSDL2Java -uri http://10.176.133.7:9080/zhptkzb/services/CarrySLPOS.jws?wsdl -p com.pcm.framework.utils -d adb -s 生成的代码则存储在bin\src下: Note:生成

一个基于.NET平台的自动化/压力测试系统设计简述(可独立运行,提供源码)

AutoTest系统设计概述 AutoTest是一个基于.NET平台实现的自动化/压力测试的系统,可独立运行于windows平台下,支持分布式部署,不需要其他配置或编译器的支持.(本质是一个基于协议的测试工具),前面还有一篇对其功能的简单介绍[http://www.cnblogs.com/lulianqi/p/4773146.html] AutoTest用于发布的部分有2个部分,主程序[AutoTest.exe]及分布式部署程序[RemoteService.exe](用于将将测试业务分布式部署到