Container With Most Water @ LeetCode (Python)

4Sum @ LeetCode (Python)

kitt posted @ 2014年4月24日 01:59 in LeetCode , 9323 阅读

先对num排序, 然后建一个dictionary d, d[num[p]+num[q]] = [(p,q) pairs 满足num[p] + num[q]], 而且这里的(p,q) pair总是满足p < q。然后用二层循环来搜, num[i]是四元组最小的数, num[j]是第二小的数, 判断d中有没有target - num[i] - num[j]这个key的时间是O(1), 如果有这个key, 就把找到的四元组加入最后的返回结果。res使用set()来去重, 否则对于输入[-3,-2,-1,0,0,1,2,3], 0会出现两个[-3, 0, 1, 2]和两个[-2, -1, 0, 3]。

 

First sort num, then build a dictionary d, d[num[p]+num[q]] = [(p,q) pairs which satisfy num[p] + num[q]], here all (p,q) pairs satisfy p < q. Then use a nested for-loop to search, num[i] is the min number in quadruplet and num[j] is the second min number. The time complexity of checking whether d has the key target - num[i] - num[j] is O(1). If this key exists, add one quadruplet to the result. Use set() to remove duplicates in res, otherwise for input [-3,-2,-1,0,0,1,2,3], 0 there will be two [-3, 0, 1, 2] and two [-2, -1, 0, 3].

class Solution:
    # @return a list of lists of length 4, [[val1,val2,val3,val4]]
    def fourSum(self, num, target):
        numLen, res, d = len(num), set(), {}
        if numLen < 4: return []
        num.sort()
        for p in xrange(numLen):
            for q in xrange(p + 1, numLen): 
                if num[p] + num[q] not in d:
                    d[ num[p] + num[q] ] = [(p,q)]
                else:
                    d[ num[p] + num[q] ].append( (p,q) )
        for i in xrange(numLen):
            for j in xrange(i + 1, numLen - 2):
                T = target - num[i] - num[j]
                if T in d:
                    for k in d[T]:
                        if k[0] > j: res.add( ( num[i], num[j], num[k[0]], num[k[1]] ) )
        return [ list(i) for i in res ]
Avatar_small
zuoyuan 说:
2014年4月24日 02:03

牛逼啊,我就剩一道word ladder ii了。看来这个4sum果然还是要用hash啊。题的原意可能就是要求用hash的,直接O(n^3)应该不是原题的意思。

Avatar_small
kitt 说:
2014年4月24日 02:09

@zuoyuan: 可能吧,我用O(n^3)过不了,你做的好快呀

Avatar_small
kitt 说:
2014年4月24日 02:11

@zuoyuan: word ladder ii 我也是一直没过, 不知道有什么好的思路

Avatar_small
zuoyuan 说:
2014年4月24日 02:45

各种参考你的解答,也断断续续做了两个月,一点也不快啊,呵呵。

Avatar_small
cold 说:
2014年5月05日 02:32

@kitt: 参考你word ladder的代码,险过word ladder ii,应该还可以优化
@zuoyuan
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return a list of lists of string
def findLadders(self, start, end, dict):
lst = []#存end的前驱单词
queue1 = [start]#存当前要遍历的单词
queue2 = []#和queue1作比较,用来判断end可不可达
ddd = {}#存路径上所有单词的前驱单词,键是单词,值是前驱单词的列表
flag = True
dddict={}.fromkeys(dict)
if start in dddict:
del dddict[start]
if end in dddict:
del dddict[end]
while flag:
for pre in queue1 :
for i in xrange(len(pre)):
part1 = pre[:i]
part2 = pre[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if pre[i] != j:
nextWord = part1 + j + part2
if nextWord == end:
if pre not in lst:
lst.append(pre)
else:
if nextWord in dddict:
if nextWord in ddd:
ddd[nextWord].append(pre)
else:ddd[nextWord] = [pre]
if nextWord not in queue2:
queue2.append(nextWord)

for tt in queue2:
del dddict[tt]
if len(lst)!=0:#最短路径在lst非0时出现
flag=False
if queue1==queue2:
return []
queue1 = queue2
queue2 = []
Solution.ret = []
for k in lst:#从end的前驱单词开始找路径
self.visit(k,[end],start,ddd)
return Solution.ret

def visit(self,root,onepath,start,d):
if root ==start:
onepath.append(root)
onepath.reverse()
Solution.ret.append(onepath)
elif root is not None:
onepath.append(root)
for x in d[root]:
self.visit(x,onepath[:],start,d)

return

Avatar_small
zuoyuan 说:
2014年5月09日 04:27

http://www.cnblogs.com/zuoyuan/p/3697045.html
@cold: 我的代码供参考。

Avatar_small
NCERT Term 2 Sample 说:
2022年9月16日 10:03

Session 2 of the Course is called Term 2, and the Class 2nd Standard students who prepared for their examination tests can download the NCERT 2nd Term Question Paper 2023 Pdf with Answers for all Languages and Subjects of the Course. Every Central Board and other Schools have conducted their examination tests as per the revised syllabus and curriculum designed and published by NCERT.NCERT Term 2 Sample Paper Class 2 Every year the NCERT has published the study and learning material for every 2nd class student studying at all locations of the country for both SA-2, FA3, FA-4 and Assignment exams to Hindi mediu.

Avatar_small
AP 10th General Scie 说:
2022年9月17日 13:21

All Andhra Pradesh State Class 10th (SSC) Students can download AP SSC Science model paper 2023 with Answer solutions in Chapter by Chapter for Physical Science, Chemistry, Biological Science and Environmental science for AP SSC Science Model Paper 2023 examination test for Unit Test-1, Unit Test-2, AP 10th General Science Question Paper Unit Test-3, Unit Test-4, and Quarterly, Half Yearly, Pre-Final with Annual final examination tests 2023. The Andhra Pradesh State Board of Secondary Education has published the General Science model paper with study material with practice paper with mock test question bank as AP 10th Biology, PS, Chemistry Model Paper 2023 for all examination tests conducted by BSEAP.

Avatar_small
civaget 说:
2023年12月02日 14:40

Elevating meta descriptions from mere summaries to enthralling invitations can make all the difference in 구글 seo click-through rates.

Avatar_small
SEO 说:
2023年12月03日 04:31

토토 Match guarantees a safe and entertaining betting experience with their carefully vetted 토토 site recommendations, making your choice simple.

Avatar_small
civaget 说:
2023年12月07日 09:32

유흥사이트 offers a unique blend of excitement and leisure. Explore the latest trends in entertainment venues and plan your next outing.

Avatar_small
civaget 说:
2023年12月08日 03:03

Join 오피아트's artistic community and embrace a world filled with imaginative brilliance.

Avatar_small
civaget 说:
2023年12月11日 08:20

Just had an incredible 제주안마 session. It's like a slice of heaven on this beautiful island. Can't recommend it enough!

Avatar_small
civaget 说:
2023年12月11日 08:33

부산오피 truly shines in Seomyeon. It's the heart of Busan's nightlife, and the energy is contagious.

Avatar_small
civaget 说:
2023年12月11日 09:00

에볼루션카지노 sets the standard high in the online casino industry. The live games and player satisfaction speak volumes about its excellence.

Avatar_small
civaget 说:
2023年12月12日 04:46 Fast deposits and withdrawals are a game-changer. 안전카지노 ensures your money is always at your fingertips.
Avatar_small
civaget 说:
2023年12月13日 07:54

Be a part of the global soccer phenomenon – join 축구중계.

Avatar_small
civaget 说:
2023年12月14日 04:32

출장마사지 is a lifesaver for business travelers like me. Oga's services are top-notch and incredibly relaxing.

Avatar_small
civaget 说:
2023年12月14日 10:21 I love your blog.. great colours & concept. Have you actually layout this excellent website on your own or maybe would an individual rely on someone else to make it work for yourself? Plz act in response when I!|m aiming to design my web site and also would like to understand where by you got the following by. thanks 스포츠중계
Avatar_small
civaget 说:
2023年12月17日 23:12

Hmm it appears like your website ate my first comment (it was super long) so I guess I'll just sum it up what I had written and say, I'm thoroughly enjoying your blog. I as well am an aspiring blog blogger but I'm still new to everything. Do you have any points for novice blog writers? I'd certainly appreciate it. 프리카지노

Avatar_small
civaget 说:
2023年12月21日 09:19 I can't praise 부달 enough for its exceptional Gyeongnam coverage. Its articles are informative, engaging, and truly enriching for travelers.
Avatar_small
civaget 说:
2023年12月23日 00:36 op사이트 순위: Your partner in navigating the digital landscape.
Avatar_small
civaget 说:
2023年12月23日 06:31

뉴토끼 is my sanctuary for all things webtoon-related.

Avatar_small
civaget 说:
2024年1月14日 04:00

천안출장마사지 is your destination for a revitalizing experience like no other.

Avatar_small
SEO 说:
2024年1月23日 02:23

You must participate in a contest for among the best blogs on the web. I will suggest this web site! The Presidential Family

Avatar_small
SEO 说:
2024年1月31日 23:10

Hi there! This is kind of off topic but I need some advice from an established blog. Is it very hard to set up your own blog? I’m not very techincal but I can figure things out pretty quick. I’m thinking about setting up my own but I’m not sure where to start. Do you have any points or suggestions? Thank you lpb piso wifi 10.0.0.1 pause time login

Avatar_small
drKimberly fungus tr 说:
2024年2月02日 23:44

Hello there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I will appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers!

Avatar_small
civaget 说:
2024年2月03日 01:03


Hello there, just became alert to your blog through Google, and found that it’s truly informative. I am going to watch out for brussels. I will appreciate if you continue this in future. A lot of people will be benefited from your writing. Cheers! drKimberly fungus treatment protocolo

Avatar_small
white garmin watch 说:
2024年2月05日 01:18

Useful information. Fortunate me I discovered your web site by accident, and I am stunned why this accident didn’t came about in advance! I bookmarked it.

Avatar_small
툰코 무협 说:
2024年2月07日 00:32

The when I just read a blog, I’m hoping that this doesnt disappoint me approximately this one. Get real, Yes, it was my method to read, but When i thought youd have something interesting to state. All I hear is a number of whining about something that you could fix should you werent too busy trying to find attention. agen murahqq

Avatar_small
seo 说:
2024年2月07日 06:39

I’m honored to obtain a call from a friend as he identified the important tips shared on your site. Browsing your blog post is a real excellent experience. Many thanks for taking into consideration readers at all like me, and I wish you the best of achievements as being a professional domain. 에볼루션카지노

Avatar_small
seo 说:
2024年2月07日 07:51

Wow this hit it to the spot we will bookmark on Bebo and also Hub pages thanks Городскую комиссию по землепользованию сменил Мосинвестконтроль | Профессиональные новости | ООО “Белго+” – Двери производства Белоруси. Продажа, установка love it And also my prayers to the people at atomic plant we hope you are OK along with safer too !!! Kudos Financial Advisers The Growth Matrix Reviews

Avatar_small
seo 说:
2024年2月10日 03:28

I am typically to blogging and i actually recognize your content. The article has actually peaks my interest. I am going to bookmark your web site and maintain checking for brand new information. Exodus Effect

Avatar_small
seo 说:
2024年2月10日 22:28

Informative Site… Hello guys here are some links that contains information that you may find useful yourselves. It’s Worth Checking out…. 셔츠룸

Avatar_small
seo 说:
2024年2月11日 22:37

How much of an unique article, keep on posting better half ダッチワイフ

Avatar_small
seo 说:
2024年2月12日 04:29

I am crazy about this blog. I have visit so many time to this blog. I was found this blog from Google. I have received a nice stuff of information. I really appreciate to meet to it and i emphasize to this blog. My curiosity to learn more and more on this blog. Dealers of nickel ribbon

Avatar_small
robinjack 说:
2024年5月28日 06:41

This way, you won’t have to worry about trying out any new and potentially risky concept. Study

Avatar_small
gsefwe 说:
2024年10月04日 06:45

WINSLOT adalah situs judi slot online dengan game slot gacor gampang menang maxwin hari ini. Akses link resmi win supaya mudah menang slot gacor hari ini. slot online

Avatar_small
escorts in dubai 说:
2024年11月09日 22:51

There are some interesting points in time on this article but I don’t know if I see all of them heart to heart. There’s some validity however I will take hold opinion till I look into it further. Good article , thanks and we would like extra! Added to FeedBurner as nicely escorts in dubai

Avatar_small
Aubreigh Wyatt Death 说:
2024年11月16日 13:58

Your blog is one of my favorites.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter