zoukankan      html  css  js  c++  java
  • 查找表_leetcode15

    #coding=utf-8
    # 解题思路:查找表 n2 20190302 找工作期间
    # 排序数组的双指针求和法 : (0,n) -> (a,b)
    # 其中a只能增加 b只能减少 : 搜索方向的问题 ,不然会到重复的状态

    class Solution(object):
    def threeSum(self, nums):
    """
    :type nums: List[int]
    :rtype: List[List[int]]
    """
    # 时间复杂度 n3
    if len(nums) < 3:
    return []
    result = []
    for i in range(len(nums) - 1):
    for j in range(i + 1, len(nums)):
    sum = nums[i] + nums[j]
    if -sum in nums:
    k = nums.index(-sum)
    if k != i and k != j:
    temp = sorted([nums[i], nums[j], nums[k]])
    if temp not in result:
    result.append(temp)
    return result



    class Solution2(object):
    def threeSum(self, nums):
    if len(nums) < 3:
    return []
    result = []
    nums = sorted(nums)
    for index, item in enumerate(nums):
    target = -item
    start = index + 1
    end = len(nums) - 1
    if item > 0 or nums[end] < 0:
    break
    if index > 0 and item == nums[index-1]:
    continue
    while start < end:
    if nums[end] < 0:
    break
    if nums[start] + nums[end] == target:
    temp_list = [nums[index], nums[start], nums[end]]
    result.append(temp_list)

    while start < end and nums[start] == nums[start+1]:
    start = start + 1
    while start < end and nums[end] == nums[end-1]:
    end = end - 1

    start = start + 1
    end = end - 1

    elif nums[start] + nums[end] < target:
    start = start + 1
    else:
    end = end - 1

    return result
  • 相关阅读:
    欧拉回路和欧拉路径
    nth_element函数
    Java读写Excel
    如何指定tomcat中session过期时间
    Java 正则表达式
    Java与模式阅读笔记(1)依赖倒转原则
    Linux vi 命令详解
    native2ascii & ascii2native
    Linux 下zip包的压缩与解压
    linux设置邮件自动转发
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546891.html
Copyright © 2011-2022 走看看