Skip to content

Commit 258856c

Browse files
committed
110
1 parent 88e473a commit 258856c

10 files changed

+533
-21
lines changed

Python/3sum.py

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
'''
2+
3+
4+
Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
5+
6+
Note:
7+
8+
The solution set must not contain duplicate triplets.
9+
10+
Example:
11+
12+
Given array nums = [-1, 0, 1, 2, -1, -4],
13+
14+
A solution set is:
15+
[
16+
[-1, 0, 1],
17+
[-1, -1, 2]
18+
]
19+
20+
21+
22+
'''
23+
24+
class Solution:
25+
def threeSum(self, nums: 'List[int]') -> 'List[List[int]]':
26+
27+
# Approach one
28+
# from collections import Counter
29+
# dic = Counter(nums)
30+
# res = []
31+
# new_nums = []
32+
# for k,v in dic.items():
33+
# if k == 0 and v > 2:
34+
# res.append([0,0,0])
35+
# new_nums.append(0)
36+
# continue
37+
# if v >= 2:
38+
# if k != 0 and -2*k in dic.keys():
39+
# res.append([k,k,-2*k])
40+
# new_nums.append(k)
41+
# else:
42+
# new_nums.append(k)
43+
44+
# nums = sorted(new_nums)
45+
# length = len(nums) - 1
46+
# for i,n in enumerate(nums):
47+
# if n > 0 : break
48+
# l, r = i + 1, length
49+
# while l < r:
50+
# result = nums[l] + nums[r] + n
51+
# if result > 0:
52+
# r -= 1
53+
# elif result == 0:
54+
# res.append([n, nums[l], nums[r]])
55+
# l += 1
56+
# r -= 1
57+
# else:
58+
# l += 1
59+
# return res
60+
61+
62+
63+
64+
65+
66+
# Approach two 排序后撞指针 O(n2)
67+
# nums = sorted(nums)
68+
# res = []
69+
# length = len(nums) - 1
70+
# for i,n in enumerate(nums[:-2]):
71+
# if i > 0 and n == nums[i-1]: continue
72+
# if n > 0 : break
73+
# l, r = i + 1, length
74+
# while l < r:
75+
# result = nums[l] + nums[r] + n
76+
# if result > 0:
77+
# r -= 1
78+
# elif result == 0:
79+
# res.append([n, nums[l], nums[r]])
80+
# l += 1
81+
# while l < r and nums[l - 1] == nums[l]:
82+
# l += 1
83+
# r -= 1
84+
# while l < r and nums[r] == nums[r + 1]:
85+
# r -= 1
86+
# else:
87+
# l += 1
88+
# return res
89+
90+
91+
92+
93+
94+
# Approach three O(j*k) faster than 98% ,但消耗的内存增加
95+
from collections import Counter
96+
dic = Counter(nums)
97+
pos = [x for x in dic if x > 0]
98+
neg = [x for x in dic if x < 0]
99+
res = []
100+
101+
if dic.get(0, 0) > 2: res.append([0, 0, 0]) # 单独处理特殊的零
102+
for x in pos: # a、b、c 三数加和为零,若 a < 0 , b > 0 , 则 a < -c < b
103+
for y in neg:
104+
s = -(x + y)
105+
if s in dic:
106+
if s == x and dic[x] > 1:
107+
res.append([x, x, y])
108+
elif s == y and dic[y] > 1:
109+
res.append([x, y, y])
110+
elif y < s < x:
111+
res.append([x, y, s])
112+
return res

Python/4sum-ii.py

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
'''
2+
3+
Given four lists A, B, C, D of integer values, compute how many tuples (i, j, k, l) there are such that A[i] + B[j] + C[k] + D[l] is zero.
4+
5+
To make problem a bit easier, all A, B, C, D have same length of N where 0 ≤ N ≤ 500. All integers are in the range of -228 to 228 - 1 and the result is guaranteed to be at most 231 - 1.
6+
7+
Example:
8+
9+
Input:
10+
A = [ 1, 2]
11+
B = [-2,-1]
12+
C = [-1, 2]
13+
D = [ 0, 2]
14+
15+
Output:
16+
2
17+
18+
Explanation:
19+
The two tuples are:
20+
1. (0, 0, 0, 1) -> A[0] + B[0] + C[0] + D[1] = 1 + (-2) + (-1) + 2 = 0
21+
2. (1, 1, 0, 0) -> A[1] + B[1] + C[0] + D[0] = 2 + (-1) + (-1) + 0 = 0
22+
23+
'''
24+
25+
26+
27+
class Solution:
28+
def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int:
29+
30+
# Approach one
31+
# length = len(A)
32+
# res = 0
33+
# dic = {}
34+
# for i in range(length):
35+
# for j in range(length):
36+
# twosum = A[i] + B[j]
37+
# dic[twosum] = dic.get(twosum, 0) + 1
38+
# for i in range(length):
39+
# for j in range(length):
40+
# res += dic.get(- C[i] - D[j], 0)
41+
# return res
42+
43+
44+
# Approach two
45+
from collections import Counter
46+
dicA , dicB ,dicC ,dicD = Counter(A), Counter(B), Counter(C), Counter(D)
47+
res = 0
48+
dic = {}
49+
for a , a_nember in dicA.items():
50+
for b , b_nember in dicB.items():
51+
dic[a+b] = dic.get(a+b,0) + a_nember * b_nember
52+
for c, c_nember in dicC.items():
53+
for d, d_nember in dicD.items():
54+
res += dic.get(-c-d,0) * c_nember * d_nember
55+
return res

Python/4sum.py

+79
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
'''
2+
3+
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
4+
5+
Note:
6+
7+
The solution set must not contain duplicate quadruplets.
8+
9+
Example:
10+
11+
Given array nums = [1, 0, -1, 0, -2, 2], and target = 0.
12+
13+
A solution set is:
14+
[
15+
[-1, 0, 0, 1],
16+
[-2, -1, 1, 2],
17+
[-2, 0, 0, 2]
18+
]
19+
20+
21+
'''
22+
23+
24+
25+
class Solution:
26+
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
27+
28+
# Approach one O(n3)
29+
# from collections import Counter
30+
# dic = Counter(nums)
31+
# res = []
32+
# nums = sorted(nums)
33+
# length = len(nums) - 1
34+
# for i in range(length-2):
35+
# if i != 0 and nums[i] == nums[i - 1]: continue # 避免重复答案
36+
# key = target - nums[i]
37+
# for j in range(i + 1, length-1):
38+
# if j != i + 1 and nums[j] == nums[j - 1]: continue # 避免重复答案
39+
# twosum = key - nums[j]
40+
# l,r = j+1 , length
41+
# while l < r:
42+
# ans = nums[l] + nums[r]
43+
# if twosum < ans:
44+
# r -= 1
45+
# elif twosum == ans:
46+
# res.append([nums[i],nums[j],nums[l],nums[r]])
47+
# r -= 1
48+
# while nums[r] == nums[r + 1] and l < r:
49+
# r -= 1
50+
# l += 1
51+
# while nums[l] == nums[l - 1] and l < r:
52+
# l += 1
53+
# else:
54+
# l += 1
55+
# return res
56+
57+
58+
59+
# Approach two O(n2)
60+
res = set()
61+
nums = sorted(nums)
62+
length = len(nums)
63+
dic = {}
64+
if length < 4 or 4 * nums[0] > target or 4 * nums[-1] < target: return []
65+
for i in range(length-1):
66+
for j in range(i+1,length):
67+
twosum = nums[i] + nums[j]
68+
if twosum in dic.keys():
69+
dic[twosum].append((i,j))
70+
else:
71+
dic[twosum] = [(i,j)]
72+
for i in range(length-1):
73+
for j in range(i+1,length):
74+
ans = target - nums[i] - nums[j]
75+
if dic.get(ans, 0) != 0:
76+
for k in dic.get(ans):
77+
if k[0] > j:
78+
res.add((nums[i] , nums[j] , nums[k[0]] , nums[k[1]] ))
79+
return list(res)

Python/contains-duplicate-ii.py

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
'''
2+
3+
Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.
4+
5+
Example 1:
6+
7+
Input: nums = [1,2,3,1], k = 3
8+
Output: true
9+
Example 2:
10+
11+
Input: nums = [1,0,1,1], k = 1
12+
Output: true
13+
Example 3:
14+
15+
Input: nums = [1,2,3,1,2,3], k = 2
16+
Output: false
17+
18+
'''
19+
20+
21+
class Solution:
22+
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
23+
# Approach one
24+
dic = {}
25+
for i , n in enumerate(nums):
26+
if n not in dic:
27+
dic[n] = i
28+
elif i - dic.get(n) <= k:
29+
return True
30+
else:
31+
dic[n] = i
32+
return False

Python/contains-duplicate-iii.py

+78
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
'''
2+
Given an array of integers, find out whether there are two distinct indices i and j in the array such that the absolute difference between nums[i] and nums[j] is at most t and the absolute difference between i and j is at most k.
3+
4+
Example 1:
5+
6+
Input: nums = [1,2,3,1], k = 3, t = 0
7+
Output: true
8+
Example 2:
9+
10+
Input: nums = [1,0,1,1], k = 1, t = 2
11+
Output: true
12+
Example 3:
13+
14+
Input: nums = [1,5,9,1,5,9], k = 2, t = 3
15+
Output: false
16+
17+
18+
'''
19+
20+
21+
class Solution:
22+
def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool:
23+
24+
# Approach one TLE
25+
# length = len(nums)
26+
# if length < 2 or t < 0: return False
27+
# l , r = 0 , 1
28+
# while l <= r:
29+
# if r > length - 1: return False
30+
# if abs(nums[r] - nums[l]) <= t:
31+
# if 0 < r - l <= k:
32+
# return True
33+
# else:
34+
# if r - l < k and r < length - 1:
35+
# r += 1
36+
# elif r - l == k or r == length - 1:
37+
# l += 1
38+
# r = l+1
39+
# else:
40+
# l += 1
41+
# else:
42+
# if r - l < k and r < length - 1:
43+
# r += 1
44+
# elif r - l == k or r == length - 1:
45+
# l += 1
46+
# r = l+1
47+
# else:
48+
# l += 1
49+
# return False
50+
51+
52+
53+
# Approach two 低效
54+
# length = len(nums)
55+
# if length < 2 or t < 0 or k < 0: return False
56+
# dic = []
57+
# for i,n in enumerate(nums):
58+
# if t == 0: # 一个超长的例子需要特殊处理
59+
# if n in dic:
60+
# return True
61+
# else:
62+
# for j in dic:
63+
# if abs(j - n) <= t:
64+
# return True
65+
# dic.append(n)
66+
# if len(dic) > k: del dic[0]
67+
# return False
68+
69+
70+
# Approach three
71+
length = len(nums)
72+
if k <= 0: return False
73+
if t == 0 and len(set(nums)) == length: return False
74+
for i in range(length - 1):
75+
for j in range(i+1, min(i+1+k , length)):
76+
if j - i <= k and abs(nums[j] - nums[i]) <= t:
77+
return True
78+
return False

Python/group-anagrams.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
'''
2+
Given an array of strings, group anagrams together.
3+
4+
Example:
5+
6+
Input: ["eat", "tea", "tan", "ate", "nat", "bat"],
7+
Output:
8+
[
9+
["ate","eat","tea"],
10+
["nat","tan"],
11+
["bat"]
12+
]
13+
Note:
14+
15+
All inputs will be in lowercase.
16+
The order of your output does not matter.
17+
18+
19+
'''
20+
21+
22+
class Solution:
23+
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
24+
25+
# Approach one
26+
dic = {}
27+
for i in strs:
28+
ii = ''.join(sorted(i))
29+
if dic.get(ii,0) != 0:
30+
dic[ii].append(i)
31+
else:
32+
dic[ii] = [i]
33+
return [i for i in dic.values()]

0 commit comments

Comments
 (0)