Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit1b1870f

Browse files
leetcode
1 parentddefede commit1b1870f

File tree

3 files changed

+110
-95
lines changed

3 files changed

+110
-95
lines changed

‎.idea/workspace.xml

Lines changed: 53 additions & 95 deletions
Some generated files are not rendered by default. Learn more aboutcustomizing how changed files appear on GitHub.

‎leetcode/1. Two Sum.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
'''
2+
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
3+
You may assume that each input would have exactly one solution.
4+
Given nums = [2, 7, 11, 15], target = 9,
5+
Because nums[0] + nums[1] = 2 + 7 = 9,
6+
return [0, 1].
7+
'''
8+
9+
classSolution():
10+
deftwoSum(self,nums,target):
11+
hashdict= {}
12+
fori,iteminenumerate(nums):
13+
if (target-item)inhashdict:
14+
return (hashdict[target-item],i)
15+
hashdict[item]=i
16+
return (-1,-1)
17+
s=Solution()
18+
print(s.twoSum([2,7,11,15],9))

‎leetcode/15. 3Sum.py

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
'''
2+
Given an array S of n integers, are there elements a, b, c in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
3+
4+
Note: The solution set must not contain duplicate triplets.
5+
6+
For example, given array S = [-1, 0, 1, 2, -1, -4],
7+
8+
A solution set is:
9+
[[-1, 0, 1],[-1, -1, 2]]
10+
'''
11+
12+
classSolution(object):
13+
defthreeSum(self,nums):
14+
ifnums==Noneorlen(nums)<3:
15+
return []
16+
eliflen(nums)==3andsum(nums)==0:
17+
return [sorted(nums)]
18+
19+
nums.sort()# sorted, O(nlogn)
20+
result,length= [],len(nums)
21+
foriinrange(length-2):
22+
ifi>0andnums[i-1]==nums[i]:
23+
continue
24+
l,r=i+1,length-1# i < l < r
25+
whilel<r:
26+
Sum=nums[i]+nums[l]+nums[r]
27+
ifSum==0:
28+
result.append([nums[i],nums[l],nums[r]])
29+
whilel<randnums[l]==nums[l+1]:# if appear same integer, l move right 1 place
30+
l+=1
31+
whilel<randnums[r]==nums[r-1]:# if appear same integer, r move left 1 place
32+
r-=1
33+
ifSum>0:
34+
r-=1
35+
else:
36+
l+=1
37+
returnresult
38+
s=Solution()
39+
print(s.threeSum([0,0,0,0,0]))

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp