zoukankan      html  css  js  c++  java
  • [Lintcode 3sum]三数之和(python,二分)

    题目链接:http://www.lintcode.com/zh-cn/problem/3sum/?rand=true#

    用这个OJ练练python…这个题意和解法就不多说了,O(n^2lgn)就行了,关键是!!python的语法…

    要想给tuple排序,如果直接sort的话会自动转成list,这个时候要再转回来。

     1 class Solution:
     2     """
     3     @param numbersbers : Give an array numbersbers of n integer
     4     @return : Find all unique triplets in the array which gives the sum of zero.
     5     """
     6     def Solution(self):
     7         pass
     8     def threeSum(self, numbers):
     9         # write your code here
    10         numbers.sort()
    11         ret = []
    12         n = len(numbers)
    13         for i in range(0, n):
    14             for j in range(i+1, n):
    15                 d = -(numbers[j] + numbers[i])
    16                 l = 0
    17                 r = n - 1
    18                 p = -1
    19                 while l <= r:
    20                     m = (l + r) >> 1
    21                     if numbers[m] == d:
    22                         p = m
    23                         break
    24                     elif numbers[m] > d:
    25                         r = m - 1
    26                     elif numbers[m] < d:
    27                         l = m + 1
    28                 if p != -1 and p != i and p != j:
    29                     ret.append((numbers[i], numbers[j], numbers[p]))
    30         nn = len(ret)
    31         for i in range(0, nn):
    32             ret[i] = list(ret[i])
    33             ret[i].sort()
    34             ret[i] = tuple(ret[i])
    35         ret = list(set(ret))
    36         return ret
  • 相关阅读:
    log.count/logrt.count/log/logrt
    datetime
    差集交集
    pandas 空df对象判断
    pyinstaller
    pysimplegui
    vi编辑实用命令
    hadoop实用命令
    查找redis安装目录
    spark streaming 读取kafka数据保存到parquet文件,redis存储offset
  • 原文地址:https://www.cnblogs.com/kirai/p/5558967.html
Copyright © 2011-2022 走看看