242.有效的字母异位词
题目链接:力扣
文章链接:代码随想录
给定两个字符串 s 和 t ,编写一个函数来判断 t 是否是 s 的字母异位词。
示例 1: 输入: s = "anagram", t = "nagaram" 输出: true
示例 2: 输入: s = "rat", t = "car" 输出: false
说明: 你可以假设字符串只包含小写字母。
思路:
定义一个数组叫做record用来上记录字符串s里字符出现的次数。
需要把字符映射到数组也就是哈希表的索引下标上,因为字符a到字符z的ASCII是26个连续的数值,所以字符a映射为下标0,相应的字符z映射为下标25。
再遍历 字符串s的时候,只需要将 s[i] - ‘a’ 所在的元素做+1 操作即可,并不需要记住字符a的ASCII,只要求出一个相对数值就可以了。 这样就将字符串s中字符出现的次数,统计出来了。
那看一下如何检查字符串t中是否出现了这些字符,同样在遍历字符串t的时候,对t中出现的字符映射哈希表索引上的数值再做-1的操作。
那么最后检查一下,record数组如果有的元素不为零0,说明字符串s和t一定是谁多了字符或者谁少了字符,return false。
最后如果record数组所有元素都为零0,说明字符串s和t是字母异位词,return true。
代码:
class Solution {
public boolean isAnagram(String s, String t) {
int[] result = new int[26];
for(int i = 0; i < s.length(); i++){
char k = s.charAt(i);
result[k - 97] += 1;
}
for( int j = 0; j < t.length(); j++){
char n = t.charAt(j);
result[n - 97] -= 1;
}
for(int obj : result){
if(obj != 0){
return false;
}
}
return true;
}
}
349. 两个数组的交集
题目链接:力扣
文章链接:代码随想录
题目:
题意:给定两个数组,编写一个函数来计算它们的交集。
思路:
class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set1 = new HashSet<> ();
Set<Integer> set2 = new HashSet<> ();
for(int i = 0; i < nums1.length; i++){
if(!set1.contains(nums1[i])){
set1.add(nums1[i]);
}
}
for(int j = 0; j < nums2.length; j++){
if(set1.contains(nums2[j])){
set2.add(nums2[j]);
}
}
int k = 0;
int[] result = new int[set2.size()];
for(int obj : set2){
result[k++]=obj;
}
return result;
}
}
202. 快乐数
题目链接:力扣
文章链接:代码随想录
题目:
编写一个算法来判断一个数 n 是不是快乐数。
「快乐数」定义为:对于一个正整数,每一次将该数替换为它每个位置上的数字的平方和,然后重复这个过程直到这个数变为 1,也可能是 无限循环 但始终变不到 1。如果 可以变为 1,那么这个数就是快乐数。
如果 n 是快乐数就返回 True ;不是,则返回 False 。
示例:
输入:19
输出:true
解释:
1^2 + 9^2 = 82
8^2 + 2^2 = 68
6^2 + 8^2 = 100
1^2 + 0^2 + 0^2 = 1
代码:
class Solution {
public boolean isHappy(int n) {
Set<Integer> set = new HashSet<> ();
while(n != 1 && !set.contains(n) ){
set.add(n);
n = getNextNumber(n);
}
return n==1;
}
private int getNextNumber(int n){
int reset = 0;
while(n > 0){
int temp = n % 10;
reset += temp * temp;
n = n / 10;
}
return reset;
}
}
1. 两数之和
题目链接:力扣
文章链接:代码随想录
题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
本题呢,我就需要一个集合来存放我们遍历过的元素,然后在遍历数组的时候去询问这个集合,某元素是否遍历过,也就是 是否出现在这个集合。
那么我们就应该想到使用哈希法了。
因为本地,我们不仅要知道元素有没有遍历过,还有知道这个元素对应的下标,需要使用 key value结构来存放,key来存元素,value来存下标,那么使用map正合适。
代码1:暴力法
class Solution {
public int[] twoSum(int[] nums, int target) {
for(int i = 0; i < nums.length; i ++){
for(int j = i + 1; j < nums.length; j++){
if(nums[i] + nums[j] == target){
int[] result = new int[]{i, j};
return result;
}
}
}
return new int[]{0};
}
}
代码2:哈希法
class Solution {
public int[] twoSum(int[] nums, int target) {
Map<Integer,Integer> map = new HashMap<> ();
int[] res = new int[2];
for(int i = 0; i < nums.length; i++){
int temp = target - nums[i];
if(map.containsKey(temp)){
res[0] = i;
res[1] = map.get(temp);
}
map.put(nums[i], i);
}
return res;
}
}