454.四数相加 ||
思路:四个数组分成两大组独立循环,遍历nums1+nums2的所有元素和并且加入到字典中,再遍历nums3+nums4,一个个去和字典存在的值比较(注意比较需要取负数)。若存在(即表示四数组相加等于0),返回字典中的Tvalue,再累加到value中;不存在返回0。
C#代码:
public class Solution {
public int FourSumCount(int[] nums1, int[] nums2, int[] nums3, int[] nums4) {
Dictionary<int, int> dict = new Dictionary<int, int>();
int value = 0;
for (int i = 0; i < nums1.Length; i++)
{
for (int j = 0; j < nums2.Length; j++)
{
int sum1 = nums1[i] + nums2[j];
dict.TryAdd(sum1, 0);
dict[sum1]++;
}
}
for (int i = 0; i < nums3.Length; i++)
{
for (int j = 0; j < nums4.Length; j++)
{
int sum2 = nums3[i] + nums4[j];
int count = dict.ContainsKey(-sum2) ? dict[-sum2] : 0;
value += count;
}
}
return value;
}
}
383.赎金信
思路:跟242.有效的字母异位词基本一样。
C#代码:
public class Solution {
public bool CanConstruct(string ransomNote, string magazine) {
Dictionary<char, int> dict = new Dictionary<char, int>();
foreach(char a in magazine){
dict.TryAdd(a,0);
dict[a]++;
}
foreach(char a in ransomNote){
dict.TryAdd(a,0);
dict[a]--;
if(dict[a] < 0){
return false;
}
}
return true;
}
}
15.三数之和
思路:取三个指针i,left,right。i循环直到数组长度-2,left和right做类似二分查找。最后得注意去重,一个是判断i是否和前面的i-1指向的元素相同,相同进入新一轮循环;另一个是加入新列表后判断left的后一项和right的前一项是否相同,相同去除再继续判断,不同跳出。
C#代码:
public class Solution {
public IList<IList<int>> ThreeSum(int[] nums) {
IList<IList<int>> list = new List<IList<int>>();
Array.Sort(nums);//重新排序
for (int i = 0; i < nums.Length - 2; i++)
{
int n1 = nums[i];
if (n1 > 0) break;//数组大于0退出
if (i > 0 && n1 == nums[i - 1]) continue;//数组下标i指向的元素在下标i-1之后出现,重新循环
int left = i + 1;
int right = nums.Length - 1;
//类似二分查找,左右指针互相靠近
while(left < right)
{
int n2 = nums[left];
int n3 = nums[right];
int sum = n1 + n2 + n3;
//总和大于0,右边靠左;总和小于0,左边靠右
if(sum > 0) { right--; }
else if(sum < 0) { left++; }
else //否则加入list中
{
list.Add(new List<int> { n1, n2, n3 });
//指针的指向跳过和n2、n3相同的元素(去重)
while(left < right && nums[left] == n2) { left++; }
while(left < right && nums[left] == n3) { right--; }
}
}
}
return list;
}
}
18.四数之和
思路:和三数之和一样套路,就是要多一个循环,还有题目提供目标值,不需要去判断数组大于0的情况
C#代码:
public class Solution
{
public IList<IList<int>> FourSum(int[] nums, int target)
{
IList<IList<int>> list = new List<IList<int>>();
Array.Sort(nums);
for (int i = 0; i < nums.Length - 3; i++)
{
int a = nums[i];
if (i > 0 && a == nums[i - 1]) { continue; }
for (int j = i + 1; j < nums.Length - 2; j++)
{
int b = nums[j];
int left = j + 1;
int right = nums.Length - 1;
if (j > i + 1 && b == nums[j - 1]) { continue; }
while (right > left)
{
int c = nums[left];
int d = nums[right];
int sum = a + b + c + d;
if (sum < target) { left++; }
else if (sum > target) { right--; }
else
{
list.Add(new List<int> { a, b, c, d });
while (right > left && nums[left] == c) { left++; }
while (right > left && nums[right] == d) { right--; }
}
}
}
}
return list;
}
}
总结:今天这几道题挺好写的,看文本解析大概知道要怎么写,麻烦点的就三数之和,考虑的东西有点难想到,多加练习就明白题目的套路,其他方面没有太大的问题。