关闭

leetcode-python 第十周

标签: leetcode
288人阅读 评论(0) 收藏 举报
分类:

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
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:12767次
    • 积分:453
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:0篇
    • 译文:14篇
    • 评论:2条
    最新评论