LeetCode刷题(五)

141. Linked List Cycle

Description

Given a linked list, determine if it has a cycle in it.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Example 1

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the second node.

在这里插入图片描述

Example 2

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

在这里插入图片描述

Example 3

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

在这里插入图片描述

Follow up

Can you solve it using O(1) (i.e. constant) memory?

思路及代码

这是一道判断链表中有无环的问题,使用快慢指针。对应的Python代码如下:

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

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        fast = head
        slow = head
        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            if slow == fast:
                return True
        return False

169. Majority Element

Description

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 1

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

Example 2

Input: [2,2,1,1,1,2,2]
Output: 2

思路及代码

  1. 第一种方法:求出现次数大于n/2的数,用一个count来计数,设置一个初始对比值num,当遍历到的数等于num的时候,count加1,否则减1。当count为0的时候,说明对比值在前面遍历过的数中出现的次数小于等于已经遍历过的数的一半,此时重新设置对比值为当前值,继续遍历。对应的Python代码如下:
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count, num = 1, nums[0]
        for i in nums[1:]:
            if not count:
                num = i
            if num == i:
                count += 1
            else:
                count -= 1
        return num
  1. 第二种方法:既然众数出现次数大于n/2,我们将数组排序后,位于数组中间的元素一定是我们要求的众数。对应的Python代码如下:
class Solution(object):
    def majorityElement(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        nums.sort()
        return nums[len(nums)//2]

32. Longest Valid Parentheses

Description

Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.

Example 1

Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"

Example 2

Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"

思路及代码

设置一个临时的列表tmp和一个记录数组,临时列表用于存储左括号对应的下标,记录数组用于记录完整的括号对应的下标,当两个下标位能构成一对括号时,数组对应下标位的值为1,其他的值为0。遍历输入字符串,当遍历到左括号时,将对应下标存入临时列表;如果不是左括号,那么判断临时列表是否为空,如果不为空,弹出临时列表最后一个元素,将记录数组对应弹出元素的下标位和当前遍历的下标值设置为1。得到完整的记录数组后,我们新建两个常量,一个maxCount用来记录当前的最大长度,一个count用来记录当前的长度。然后遍历记录数组,如果值不为0,那么count加1;如果值为0,说明当前位置没有完整的括号,更新maxCount值,重新设置count值为0,直到遍历完整个记录数组,对应的Python代码如下:

class Solution(object):
    def longestValidParentheses(self, s):
        """
        :type s: str
        :rtype: int
        """
        tmp, array = [], [0] * len(s)
        count, maxCount = 0, 0
        for i in range(len(s)):
            if s[i] == '(':
                tmp.append(i)
            elif tmp:
                array[tmp.pop()], array[i] = 1, 1
        for i in array:
            if i:
                count += 1
            else:
                maxCount = max(count, maxCount)
                count = 0
        return max(maxCount, count)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值