目录
原题链接:242. 有效的字母异位词 - 力扣(LeetCode)
原题链接:349. 两个数组的交集 - 力扣(LeetCode)
LeetCode242:有效的字母异位词
题目描述:
给定两个字符串 s
和 t
,编写一个函数来判断 t
是否是 s
的字母异位词。
注意:若 s
和 t
中每个字符出现的次数都相同,则称 s
和 t
互为字母异位词。
示例 1:
输入: s = "anagram", t = "nagaram" 输出: true
解题思路:
1.使用字典
使用字典dic存储一个字符串的字符和字符个数,Key代表字符,Value代表个数,遍历另一个字符,当其字符在dic存在时 将字符个数减一,字符个数为零时从字典中移除。最后判断字典中的是否还有字符,如果没有则返回true
public class Solution
{
public bool IsAnagram(string s, string t)
{
Dictionary<char, int> dic = new Dictionary<char, int>();
foreach (char c in s)
{
if (dic.ContainsKey(c))
{
dic[c]++;
}
else
{
dic.Add(c, 1);
}
}
foreach (char c in t)
{
if (dic.ContainsKey(c))
{
dic[c]--;
if (dic[c]==0)
{
dic.Remove(c);
}
}
else
{
dic.Add(c, 1);
}
}
if (dic.Count==0)
{
return true;
}
else
{
return false;
}
}
}
原题链接:242. 有效的字母异位词 - 力扣(LeetCode)
LeetCode349:两数组交集
题目描述:
给定两个数组 nums1
和 nums2
,返回 它们的交集 。输出结果中的每个元素一定是 唯一 的。我们可以 不考虑输出结果的顺序 。
示例 1:
输入:nums1 = [1,2,2,1], nums2 = [2,2] 输出:[2]
解题思路:
1.使用HashSet
创建set1和set2,set1来存储nums1的 元素,遍历nums2,如果遇到nums2的元素在set1中存在,则将该元素加到set2中。
public class Solution
{
public int[] Intersection(int[] nums1, int[] nums2)
{
HashSet<int> set1 = new HashSet<int>();
HashSet<int> set2 = new HashSet<int>();
foreach (int x in nums1)
{
set1.Add(x);
}
foreach (int item in nums2)
{
if (set1.Contains(item))
{
set2.Add(item);
}
}
return set2.ToArray();
}
}
原题链接:349. 两个数组的交集 - 力扣(LeetCode)
LeetCode202:快乐数
题目描述:
编写一个算法来判断一个数 n
是不是快乐数。
「快乐数」 定义为:
- 对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和。
- 然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。
- 如果这个过程 结果为 1,那么这个数就是快乐数。
如果 n
是 快乐数 就返回 true
;不是,则返回 false
。
示例 1:
输入:n = 19 输出:true 解释: 12 + 92 = 82 82 + 22 = 68 62 + 82 = 100 12 + 02 + 02 = 1
解题思路:
1.使用HashSet:
创建HashSet存储平方和,当平方和重复出现时,返回false,当平方和==1时,返回true
public class Solution
{
public bool IsHappy(int n)
{
HashSet<int> visited = new HashSet<int>();
int sum = n;
while (true)
{
sum = GetSum(sum);
if(sum==1)
return true;
else
{
if(visited.Contains(sum))
return false;
else
visited.Add(sum);
}
}
}
public int GetSum(int n)
{
int sum = 0;
while (n > 0)
{
sum += (n%10)*(n%10);
n /= 10;
}
return sum;
}
}
原题链接:202. 快乐数 - 力扣(LeetCode)
LeetCode1:两数之和
题目描述:
给定一个整数数组 nums
和一个整数目标值 target
,请你在该数组中找出 和为目标值 target
的那 两个 整数,并返回它们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。
你可以按任意顺序返回答案。
示例 1:
输入:nums = [2,7,11,15], target = 9 输出:[0,1] 解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。
解题思路:
1.使用字典:
注意字典中Key,和Value代表的值,Key代表数值元素,Value代表元素下标
public class Solution
{
public int[] TwoSum(int[] nums, int target)
{
Dictionary<int,int> dic = new Dictionary<int,int>();
for (int i = 0; i < nums.Length; i++)
{
int temp = target - nums[i];
if (dic.ContainsKey(temp) && dic[temp]!=i)
{
return new int[2] { i, dic[temp] };
}
else if(!dic.ContainsKey(nums[i]))
{
dic.Add(nums[i], i);
}
}
return new int[2];
}
}