leetcode-python 第十周

原创 2016年08月30日 19:52:16

LeetCode Online Judge
https://leetcode.com/

1. Three Sum [252ms]

# 方法1:先确定一个变量i,然后用两个指针搜索
# 注意两次去重
class Solution(object):
    def threeSum(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if len(nums) < 3: return []

        ans = []
        nums.sort()
        i = 0
        while i < len(nums) - 2:
            print(i)
            start, end = i + 1, len(nums) - 1
            while start < end:
                if nums[i] + nums[start] + nums[end] == 0:
                    ans.append([nums[i], nums[start], nums[end]])
                    # 去重
                    while start < end and nums[start] == nums[start+1]:
                        start += 1
                    start += 1
                elif nums[i] + nums[start] + nums[end] < 0:
                    start += 1
                else:
                    end -= 1
            # 去重
            while i+1 < len(nums) and nums[i] == nums[i+1]:
                i += 1
            i += 1
        return ans 

2.Longest Substring Without Repeating Characters

# 方法1:双重循环,一定超时
# 方法2:头指针当遇到重复时就往后缩,顺便删除记录
# 尾指针当遇到不同元素时往后,还有就是更新完毕也要+1
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        if len(s) < 2:
            return len(s)

        ans = 0
        d = {}
        low = 0
        d[s[low]] = 0

        tmp = 1
        high = low + 1
        while high < len(s):
            if s[high] in d.keys():
                ans = max(ans, tmp)
                index = d[s[high]]
                while low <= index:
                    del d[s[low]]
                    tmp -= 1
                    low += 1
                d[s[high]] = high
                high += 1
                tmp += 1
            else:
                d[s[high]] = high
                tmp += 1
                high += 1
        return max(ans, tmp)

3. Maximum Product Subarray [64ms]


# 方法1:除了保存最大数,还要保存一个最小数,防止忽略了负数乘负数
class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if len(nums) < 2 :
            return nums[0]

        dpmax = [nums[i] for i in range(len(nums))]
        dpmin = [nums[i] for i in range(len(nums))]
        ans = nums[0]

        for i in range(1, len(nums)) :
            dpmin[i] = min(dpmin[i], dpmin[i-1] * nums[i], dpmax[i-1] * nums[i])
            dpmax[i] = max(dpmax[i], dpmax[i-1] * nums[i], dpmin[i-1] * nums[i])
            ans = max(ans, dpmax[i])
        return ans

4.Median of Two Sorted Arrays [148ms]

# http://blog.csdn.net/yutianzuijin/article/details/11499917/
class Solution(object):
    def findMedianSortedArrays(self, nums1, nums2):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :rtype: float
        """
        lth = len(nums1) + len(nums2)
        mid = int(lth / 2)
        if lth & 0x1:
            return self.findKth(nums1, nums2, mid + 1) # 奇数,终止条件为k==1
        else:
            return (self.findKth(nums1, nums2, mid) + self.findKth(nums1, nums2, mid + 1)) / 2. # 偶数

    def findKth(self, nums1, nums2, k):
        if len(nums1) > len(nums2):
            return self.findKth(nums2, nums1, k) # 默认nums1的长度小于nums2
        if len(nums1) == 0:
            return nums2[k-1] 
        if k == 1:
            return min(nums1[0], nums2[0])

        sub1 = int(min(k / 2, len(nums1)))
        sub2 = k - sub1

        if nums1[sub1 - 1] < nums2[sub2 - 1]:
            return self.findKth(nums1[sub1:], nums2, k - sub1)
        elif nums1[sub1 - 1] > nums2[sub2 - 1]:
            return self.findKth(nums1, nums2[sub2:], k - sub2)
        else:
            return nums1[sub1 - 1]

5. Sprial Matrix [64ms]

class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        ans = []
        if len(matrix) < 1 :
            return ans
        if len(matrix) == 1 and len(matrix[0]) == 1 :
            ans.append(matrix[0][0])
            return ans


        cnt = 0
        clen = len(matrix) - 1
        rlen = len(matrix[0]) - 1
        lth = len(matrix) * len(matrix[0])
        c = 0
        r = 0

        while True :
            for j in range(r, r+rlen) :
                ans.append(matrix[c][j])
                cnt += 1
                if cnt >= lth : return ans

            for i in range(c, c+clen) :
                ans.append(matrix[i][r+rlen])
                cnt += 1
                if cnt >= lth : return ans

            for j in range(r+rlen, r, -1) :
                ans.append(matrix[c+clen][j])
                cnt += 1
                if cnt >= lth : return ans

            for i in range(c+clen, c, -1) :
                ans.append(matrix[i][r])
                cnt += 1
                if cnt >= lth : return ans

            c += 1
            r += 1
            clen -= 2
            rlen -= 2

            if rlen < 0 :
                rlen = 0
            if clen < 0 :
                clen = 0

            if c + clen == c and r == r + rlen:
                ans.append(matrix[c+clen][c])
                cnt += 1
                if cnt >= lth : return ans

        return ans

6. Two Sum II [64ms]


# 方法1:双指针法
class Solution(object):
    def twoSum(self, numbers, target):
        """
        :type numbers: List[int]
        :type target: int
        :rtype: List[int]
        """
        low, high = 0, len(numbers) - 1
        while low < high:
            if numbers[low] + numbers[high] < target:
                low += 1
            elif numbers[low] + numbers[high] > target:
                high -= 1
            else:
                return [low + 1, high + 1]

7.Valid Anagram [104ms]

# 方法1:哈希表
class Solution(object):
    def isAnagram(self, s, t):
        """
        :type s: str
        :type t: str
        :rtype: bool
        """
        if len(s) != len(t):
            return False

        cnt = {}
        for s_i in range(len(s)):
            try:
                cnt[s[s_i]] += 1
            except:
                cnt[s[s_i]] = 1

        for t_i in range(len(t)):
            try:
                cnt[t[t_i]] -= 1
                if cnt[t[t_i]] == 0:
                    del cnt[t[t_i]]
            except:
                return False

        return True
版权声明:本文为博主原创文章,转载请表明出处。

LeetCode题解 第十周

1. Container With Most Water https://leetcode.com/problems/container-with-most-water/description/ ...

第十周:( LeetCode552) Student Attendance Record II(c++)

这是一道动态规划的题目,leetcode的划分的难度为Hard。其实思路并不难,但是 AC的过程略有曲折。...

Leetcode第十周周赛Smarking Algorithm Contest

Leetcode 周赛 440. K-th Smallest in Lexicographical Order 439. Ternary Expression Parser 438. Find All...
  • NachtZ
  • NachtZ
  • 2016年10月23日 12:42
  • 388

【python】【leetcode】【算法题目9—Palindrome Number】

题目原文: Determine whether an integer is a palindrome. Do this without extra space. (不用额外的空间来判断一个整形数字是不...

Python学习(Leetcode 算法题解【1~20】)

掌握了python的基础概念,并不意味着就可以使用python来进行项目开发了。学习一门编程语言时,对于概念的掌握只是基础。用该语言去解决实际问题,并在解决问题的过程中学习才是学一门语言时费时较长的部...

【算法——Python实现】快速排序的优化:三路快速排序及Leetcode题目应用

相比于普通的快速排序,优化点在于: 1.解决数组近乎有序的情况下算法复杂度会退化为O(n2)级别的问题 2.解决数组中有大量重复元素带来的复杂度退化问题import random def quic...

leetcode226题 题解 翻译 C语言版 Python版

226. Invert Binary Tree Invert a binary tree. 4 / \ 2 7 / \ / \ 1 3 6 9 to ...

[leetcode: Python]405. Convert a Number to Hexadecimal

Title: Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two...
  • NXHYD
  • NXHYD
  • 2017年05月16日 17:18
  • 212

【LEETCODE】376- Wiggle Subsequence [Python]

题目376 wiggle subsequence
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:leetcode-python 第十周
举报原因:
原因补充:

(最多只允许输入30个字)