454 四数相加II
func fourSumCount(nums1 []int, nums2 []int, nums3 []int, nums4 []int) int {
count12 := make(map[int]int)
count := 0
length := len(nums1)
for i := 0 ; i < length ; i++{
for j := 0 ; j < length ; j++{
sum := nums1[i] + nums2[j]
count12[sum]++
}
}
for i := 0 ; i < length ; i++{
for j := 0 ; j < length ; j++{
sum := nums3[i] + nums4[j]
if(count12[0-sum] > 0){
count = count + count12[0-sum]
}
}
}
return count
}
383 赎金信
func canConstruct(ransomNote string, magazine string) bool {
a := make(map[byte]int)
for i := 0 ; i < len(magazine) ; i++{
a[magazine[i]]++
}
for i := 0 ; i < len(ransomNote) ; i++{
if(a[ransomNote[i]] > 0){
a[ransomNote[i]]--
}else{
return false
}
}
return true
}
15 三数之和
func threeSum(nums []int) [][]int {
res := [][]int{}
sort.Ints(nums)
length := len(nums)
for i := 0 ; i < length-2 ; i++{
if(nums[i] > 0){
return res
}
if(i > 0 && nums[i] == nums[i-1]){
continue
}
n1 := nums[i]
l,r := i + 1,length-1
for l < r{
n2,n3 := nums[l],nums[r]
sum := n1 + n2 + n3
if(sum == 0){
res = append(res , []int{n1,n2,n3})
for l < r && n2 == nums[l]{
l++
}
for l < r && n3 == nums[r]{
r--
}
}else if(sum > 0){
r--
}else{
l++
}
}
}
return res
}
18 四数之和
func fourSum(nums []int, target int) [][]int {
res := [][]int{}
length := len(nums)
sort.Ints(nums)
for i := 0 ; i < length - 3 ; i++{
if(i > 0 && nums[i] == nums[i-1]){
continue
}
n1 := nums[i]
for j := i + 1 ; j < length - 2 ; j++{
if(nums[i] > 0 && nums[j] + nums[i] > target){
return res
}
if(j > i + 1 && nums[j] == nums[j-1]){
continue
}
n2 := nums[j]
l,r := j + 1 , length - 1
for r > l{
n3 , n4 := nums[l] , nums[r]
sum := n1 + n2 + n3 + n4
if(sum == target){
res = append(res , []int{n1 , n2 , n3 , n4})
for r > l && n3 == nums[l]{
l++
}
for r > l && n4 == nums[r]{
r--
}
}else if(sum > target){
r--
}else{
l++
}
}
}
}
return res
}
总结
15 和 18 算是一个类型的题了… 二刷的时候再做一遍 mark一下