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
  • 相关阅读:
    MySql给表中某字段插入随机数
    MySql 基本语法_数据操作
    thinkphp中模板继承
    thinkphp中模块和操作映射
    如何让ThinkPHP的模板引擎达到最佳效率
    ThinkPHP访问不存在的模块跳到404页面
    thinkphp中I方法
    thinkphp中field方法
    thinkphp中F方法
    thinkphp中where方法
  • 原文地址:https://www.cnblogs.com/lux-ace/p/10546891.html
Copyright © 2011-2022 走看看