454.四数相加II 4Sum II
两个nested loop去reduce runtime complexity
Python解法
class Solution(object):
def fourSumCount(self, nums1, nums2, nums3, nums4):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:type nums4: List[int]
:rtype: int
"""
record = {}
count = 0
for i in nums1:
for j in nums2:
record[i+j] = record.get(i+j, 0) + 1
for i in nums3:
for j in nums4:
if (0 - (i+j)) in record:
count += record[0 - (i+j)]
return count
C++解法
class Solution {
public:
int fourSumCount(vector<int>& nums1, vector<int>& nums2, vector<int>& nums3, vector<int>& nums4) {
std::unordered_map<int, int> record;
int count = 0;
for (int i = 0; i < nums1.size(); i++){
for (int j = 0; j < nums2.size(); j++){
record[nums1[i] + nums2[j]]++;
}
}
for (int i = 0; i < nums3.size(); i++){
for (int j = 0; j < nums4.size(); j++){
int target = 0 - (nums3[i] + nums4[j]);
if (record.find(target) != record.end()){
count += record[target];
}
}
}
return count;
}
};
383. 赎金信 Ransom Note
Python解法
用dictionary
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
record = {}
for element in magazine:
record[element] = record.get(element, 0) + 1
for element in ransomNote:
if element not in record or record[element] == 0:
return False
else:
record[element] -= 1
return True
用数组
class Solution(object):
def canConstruct(self, ransomNote, magazine):
"""
:type ransomNote: str
:type magazine: str
:rtype: bool
"""
letterNote = [0] * 26
letterMagazine = [0] * 26
for element in magazine:
letterMagazine[ord(element) - ord('a')] += 1
for element in ransomNote:
letterNote[ord(element) - ord('a')] += 1
return all(letterNote[i] <= letterMagazine[i] for i in range(26))
C++解法
class Solution {
public:
bool canConstruct(string ransomNote, string magazine) {
int record[26] = {0};
if (ransomNote.size() > magazine.size()){
return false;
}
for (int i = 0; i < magazine.size(); i++){
record[magazine[i] - 'a']++;
}
for (int i = 0; i < ransomNote.size(); i++){
if (record[ransomNote[i] - 'a'] == 0){
return false;
} else {
record[ransomNote[i] - 'a']--;
}
}
return true;
}
};
15. 三数之和 3Sum
直接用哈希法时间复杂度O(N^2),空间复杂度O(N),无法满足题目条件+很多bug
C++解法
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++){
if (nums[i] > 0){
// if the smallest number is not negative, sum cannot be 0
break;
}
if (i >0 && nums[i] == nums[i-1]){
// remove duplicate a
continue;
}
unordered_set<int> set;
for (int j = i+1; j < nums.size(); j++){
if (j > i + 2 && nums[j] == nums[j-1] && nums[j-1] == nums[j-2]){
// duplicate b
continue;
}
int c = 0 - nums[i] - nums[j];
if (set.find(c) != set.end()){
result.push_back({nums[i], nums[j], c});
set.erase(c); // remove duplicate c
} else {
set.insert(nums[j]);
}
}
}
return result;
}
};
为了提高运算速度,我们需要使用双指针法。
首先sort整个nums,最小数在钱,最大数在后,两个指针从两头往内移动,加上在中间的指针,找到符合题目要求的sum为0的组合。
C++解法
class Solution {
public:
vector<vector<int>> threeSum(vector<int>& nums) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++){
if (nums[i] > 0){
return result;
}
if (i > 0 && nums[i] == nums[i-1]){
continue;
}
int left = i + 1;
int right = nums.size() - 1;
while (right > left){
if (nums[i] + nums[left] + nums[right] > 0) right--;
else if (nums[i] + nums[left] + nums[right] < 0) left++;
else {
result.push_back(vector<int>{nums[i], nums[left], nums[right]});
while (right > left && nums[right] == nums[right - 1]) right--;
while (right > left && nums[left] == nums[left + 1]) left++;
right--;
left++;
}
}
}
return result;
}
};
Python解法
class Solution(object):
def threeSum(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
nums.sort()
for i in range(len(nums)):
if (nums[i] > 0):
return result
if (i > 0 and nums[i] == nums[i-1]):
continue
left = i + 1
right = len(nums) - 1
while (right > left):
threeSum = nums[i] + nums[left] + nums[right]
if (threeSum == 0):
result.append([nums[i], nums[left], nums[right]])
while (right > left and nums[left] == nums[left + 1]):
left += 1
while (right > left and nums[right] == nums[right - 1]):
right -= 1
right -= 1
left += 1
elif (threeSum < 0):
left += 1
elif (threeSum > 0):
right -= 1
return result
18. 四数之和
和可能是正的也可能是负的!!!和三数之和的sum为0情况不同!!!
C++解法
注意sum overflow
class Solution {
public:
vector<vector<int>> fourSum(vector<int>& nums, int target) {
vector<vector<int>> result;
sort(nums.begin(), nums.end());
for (int i = 0; i < nums.size(); i++){
if (nums[i] > target && nums[i] >= 0){
break;
}
if (i > 0 && nums[i] == nums[i-1]){
continue;
}
for (int j = i + 1; j < nums.size(); j++){
if (nums[i] + nums[j] > target && nums[i] + nums[j] >= 0) {
break;
}
if (j > i + 1 && nums[j] == nums[j-1]){
continue;
}
int left = j + 1;
int right = nums.size() - 1;
while (right > left){
long fourSum = (long) nums[i] + nums[j] + nums[left] + nums[right];
if (fourSum == target){
result.push_back(vector<int>{nums[i], nums[j], nums[left], nums[right]});
while (right > left && nums[left] == nums[left+1]){
left++;
}
while (right > left && nums[right] == nums[right-1]){
right--;
}
left++;
right--;
}
else if (fourSum > target){
right--;
} else {
left++;
}
}
}
}
return result;
}
};
Python解法
class Solution(object):
def fourSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[List[int]]
"""
nums.sort()
result = []
for i in range(len(nums)):
if (nums[i] > target and target > 0):
break
if (i > 0 and nums[i] == nums[i-1]):
continue
for j in range(i+1, len(nums)):
if (j > i+1 and nums[j] == nums[j-1]):
continue
if (nums[i] + nums[j] > target and target > 0):
break
left = j + 1
right = len(nums) - 1
while (right > left):
fourSum = nums[i] + nums[j] + nums[left] + nums[right]
if (fourSum == target):
result.append([nums[i], nums[j], nums[left], nums[right]])
while (right > left and nums[left] == nums[left+1]):
left += 1
while (right > left and nums[right] == nums[right-1]):
right -= 1
left += 1
right -= 1
elif (fourSum > target):
right -= 1
else:
left += 1
return result